要做一个excel的导入和导出,先说导入吧,我的方案有两个,一是使用jQuery读取excel表中的数据后,将数据以json字符串的形式传给视图,在视图中直接操作数据库,主要的难点是使用js读取excel,代码如下:
<script>
function readThis(){
var tempStr = "";
var filePath= document.all.upfile.value;
var oXL = new ActiveXObject("Excel.application");
var oWB = oXL.Workbooks.open(filePath);
oWB.worksheets(1).select();
var oSheet = oWB.ActiveSheet;
try{
for(var i=2;i<46;i++){
if(oSheet.Cells(i,2).value =="null" || oSheet.Cells(i,3).value =="null" )
break;
var a = oSheet.Cells(i,2).value.toString()=="undefined"?"":oSheet.Cells(i,2).value;
tempStr+=(" "+oSheet.Cells(i,2).value+
" "+oSheet.Cells(i,3).value+
" "+oSheet.Cells(i,4).value+
" "+oSheet.Cells(i,5).value+
" "+oSheet.Cells(i,6).value+"\n");
}
}catch(e){
//alert(e);
document.all.txtArea.value = tempStr;
}
document.all.txtArea.value = tempStr;
oXL.Quit();
CollectGarbage();
}
</script>
<html>
<input type="file" id="upfile" /><input type="button" οnclick="readThis();" value="读取">
<br>
<textarea id="txtArea" cols=50 rows=10></textarea>
</html>
方案二是直接将文件以数据流的形式传到视图中:
使用django框架接收文件数据流:
首先填写表单:
<form id="student_excel_form" action="/batchAddStudent/" enctype="multipart/form-data" method="post">
<input id="ExcelUpload" type="file" style="height:20px;width:211px;" name="ExcelUpload">
</form>
js代码:
("body").on("click","#buttonloadin",function(){
$("#student_excel_form").attr("action","/batchAddStudent/");
$.ajaxSetup({
async : false
});
$("#student_excel_form").ajaxSubmit({
resetForm:false,
dataType:'json',
success:function(data){
if(data=1){alert("导入成功");}
else if(data=-1){alert("excel表格式错误");}
else{alert("导入失败");}
}
});
location.href="/redirectToStudentinfo/?oragnizationid="+$("#LastPageOrganizatonid").val()+"&selectway="+$("#LastPageSelectWay").val()+"&hiddenselectText="+$("#LastPageSelectThing").val();
});
当文件传入视图后,django使用request.FILE进行接收,并将它保存到服务器中,这里使用到了django自带的File Uploads,可参考(http://www.cnblogs.com/linxiyue/p/4038436.html)和(http://stevezhou.info/django/article_49.html)
UploadedFile
UploadedFile是类文件对象,具有以下方法和属性:
UploadedFile.read()
读取整个上传文件的数据,文件较大时慎用。
UploadedFile.multiple_chunks(chunk_size=None)
判断文件是否足够大,一般为2.5M
UploadedFile.chunks(chunk_size=None)
返回一个生成器对象,当multiple_chunks()为True时应该使用这个方法来代替read().
UploadedFile.name
上传文件的name。
UploadedFile.size
上传文件的大小。
UploadedFile.content_type
上传文件时的content_type报头,例如(e.g. text/plain or application/pdf).
UpladedFile.charset
编码
存储文件
想将上传的文件存储在本地时:
1
2
3
4
|
f=request.FILES[
'image'
]
with
open(
'some/file/name.txt'
,
'wb+'
) as destination:
for
chunk
in
f.chunks():
destination.write(chunk)
|
我在项目中写的视图代码如下:
if req.FILES.has_key('ExcelUpload'):
ExcelUpload=req.FILES['ExcelUpload']
name=str(time.strftime('%Y%m%d%H%M%S'))
with open(os.path.join(basePath,"webStatic/xls/"+name+".xls"), 'wb+') as destination:
for chunk in ExcelUpload.chunks():
destination.write(chunk)
将文件保存到服务器后,再使用Python自带的xlrd进行excel进行读取:
首先先在Ubuntu上安装Python的xlrd和xlwt包,可参考如下简单的安装方法:
比如Ubuntu下Python读写excel库
sudo easy_install xlrd
sudo easy_install xlwt
sudo easy_install xlutils
sudo easy_install pip
xlrd和xlwt使用详解(可参考http://itweb.me/python-excel/ 以及http://www.cnblogs.com/lhj588/archive/2012/01/06/2314181.html 以及http://www.jb51.net/article/60510.htm):
- 1: import xlrd #引入包
- 2: book = xlrd.open_workbook("myfile.xls")
- 3: #创建一个book class,打开excel文件
- 4: print "The number of worksheets is", book.nsheets
- 5: # nsheets属性记录一个excel文件中有多少个sheet
- 6: print "Worksheet name(s):", book.sheet_names()
- 7: #返回sheet name的list
- 8: sh = book.sheet_by_index(0)
- 9: #获取一个sheet对象
- 10: print sh.name, sh.nrows, sh.ncols
- 11: # sheet的属性:name,rows,cols
- 12: print "Cell D30 is", sh.cell_value(rowx=29, colx=3)
- 13: #定位一个cell
- 14: for rx in range(sh.nrows):
另外,Python还有其他比较好的第三方库对excel进行读写,列如 PyExcelerator,该库写功能很强大,但是读功能没有xlrd强大,详情参见(http://blog.csdn.net/suofiya2008/article/details/5589627)
- 15: print sh.row(rx) #按照row输出excel数据