Excel Data read




라이브러리 설치

0. pip가 설치되어있지 않다면 먼저 설치

$ sudo easy_install pip


1. pip를 이용해서 openpyxl 라이브러리 설치

$ sudo pip install openpyxl




2. 기본 활용

>>> from openpyxl import load_workbook
>>> wb = load_workbook(filename = 'empty_book.xlsx')
>>> sheet_ranges = wb['range names']
>>> print(sheet_ranges['D18'].value)
3











로컬에서 MultiPartForm 전송시 유용한 class


import itertools
import mimetools
import mimetypes
from cStringIO import StringIO
import urllib
import urllib2

class MultiPartForm(object):
    """Accumulate the data to be used when posting a form."""

    def __init__(self):
        self.form_fields = []
        self.files = []
        self.boundary = mimetools.choose_boundary()
        return
    
    def get_content_type(self):
        return 'multipart/form-data; boundary=%s' % self.boundary

    def add_field(self, name, value):
        """Add a simple field to the form data."""
        self.form_fields.append((name, value))
        return

    def add_file(self, fieldname, filename, fileHandle, mimetype=None):
        """Add a file to be uploaded."""
        body = fileHandle.read()
        if mimetype is None:
            mimetype = mimetypes.guess_type(filename)[0] or 'application/octet-stream'
        self.files.append((fieldname, filename, mimetype, body))
        return
    
    def __str__(self):
        """Return a string representing the form data, including attached files."""
        # Build a list of lists, each containing "lines" of the
        # request.  Each part is separated by a boundary string.
        # Once the list is built, return a string where each
        # line is separated by '\r\n'.  
        parts = []
        part_boundary = '--' + self.boundary
        
        # Add the form fields
        parts.extend(
            [ part_boundary,
              'Content-Disposition: form-data; name="%s"' % name,
              '',
              value,
            ]
            for name, value in self.form_fields
            )
        
        # Add the files to upload
        parts.extend(
            [ part_boundary,
              'Content-Disposition: file; name="%s"; filename="%s"' % \
                 (field_name, filename),
              'Content-Type: %s' % content_type,
              '',
              body,
            ]
            for field_name, filename, content_type, body in self.files
            )
        
        # Flatten the list and add closing boundary marker,
        # then return CR+LF separated data
        flattened = list(itertools.chain(*parts))
        flattened.append('--' + self.boundary + '--')
        flattened.append('')
        return '\r\n'.join(flattened)

if __name__ == '__main__':
    # Create the form with simple fields
    form = MultiPartForm()
    form.add_field('firstname', 'Doug')
    form.add_field('lastname', 'Hellmann')
    
    # Add a fake file
    form.add_file('biography', 'bio.txt', 
                  fileHandle=StringIO('Python developer and blogger.'))

    # Build the request
    request = urllib2.Request('http://localhost:8080/')
    request.add_header('User-agent', 'PyMOTW (http://www.doughellmann.com/PyMOTW/)')
    body = str(form)
    request.add_header('Content-type', form.get_content_type())
    request.add_header('Content-length', len(body))
    request.add_data(body)

    print
    print 'OUTGOING DATA:'
    print request.get_data()

    print
    print 'SERVER RESPONSE:'
    print urllib2.urlopen(request).read()


참고:
https://pymotw.com/2/urllib2/


UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128)



문서 상단에 아래와 같이 선언시 해결 가능


import sys
reload(sys)
sys.setdefaultencoding('utf-8')




사용하면 위험하다는 의견과 괜찮다는 의견이 분분하긴 한데 테스트 결과 문제는 없었다.



참고 :
http://stackoverflow.com/questions/3828723/why-should-we-not-use-sys-setdefaultencodingutf-8-in-a-py-script

SyntaxError: Non-ASCII character ......  but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details



최상단에 해당 문서의 인코딩을 선언하면 된다.
# -*- coding: utf-8 -*-



 // 최대 바이트 제한
function fnMaxByte(e, max) {
    var $target = $(e.target);  
    var byteCount = getByteLength($target.val());  
    if (byteCount > max) {
        var rtnStr = $target.val();      
        var rtnByte = getByteLength(rtnStr);
        var leng = rtnStr.length;
        while (rtnByte > max) {
            rtnStr = rtnStr.substr(0, leng--);
            rtnByte = getByteLength(rtnStr);
        }
        $target.val(rtnStr);
    } else {
        $($target.closest('div.row')).find('.limitTextNum span').text(byteCount);    }
}


// 바이트 카운트
function getByteLength(s,b,i,c){
    for(b=i=0;c=s.charCodeAt(i++);b+=c>>11?3:c>>7?2:1);
    return b;
}





http://hangaebal.blogspot.kr/2015/09/javascript-string-byte-length.html

+ Recent posts