




版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1、1. packagemon.utils;2. importjava.io.OutputStream;3. importjava.util.List;4. importjavax.servlet.http.HttpServletResponse;5. importorg.apache.struts2.ServletActionContext;6. importjava.lang.reflect.Field;7. 8. importjxl.Workbook;9. importjxl.format.Alignment;10. importjxl.format.Border;11. importjxl
2、.format.BorderLineStyle;12. importjxl.format.VerticalAlignment;13. importjxl.write.Label;14. importjxl.write.WritableCellFormat;15. importjxl.write.WritableFont;16. importjxl.write.WritableSheet;17. importjxl.write.WritableWorkbook;18. /*19. *authorlsf20. */21. publicclassExportExcel22. /*23. *param
3、fileNameEXCEL文件名称24. *paramlistTitleEXCEL文件第一行列标题集合25. *paramlistContentEXCEL文件正文数据集合26. *return27. */28. publicfinalstaticStringexportExcel(StringfileName,StringTitle,ListlistContent)29. Stringresult=系统提示:Excel文件导出成功!;30. /以下开始输出到EXCEL31. try32. /定义输出流,以便打开保存对话框_begin33. HttpServletResponseresponse
4、=ServletActionContext.getResponse();34. OutputStreamos=response.getOutputStream();/取得输出流35. response.reset();/清空输出流36. response.setHeader(Content-disposition,attachment;filename=+newString(fileName.getBytes(GB2312),ISO8859-1);37. /设定输出文件头38. response.setContentType(application/msexcel);/定义输出类型39. /定
5、义输出流,以便打开保存对话框_end40. 41. /*创建工作簿*/42. WritableWorkbookworkbook=Workbook.createWorkbook(os);43. 44. /*创建工作表*/45. 46. WritableSheetsheet=workbook.createSheet(Sheet1,0);47. 48. /*设置纵横打印(默认为纵打)、打印纸*/49. jxl.SheetSettingssheetset=sheet.getSettings();50. sheetset.setProtected(false);51. 52. 53. /*设置单元格字体
6、*/54. WritableFontNormalFont=newWritableFont(WritableFont.ARIAL,10);55. WritableFontBoldFont=newWritableFont(WritableFont.ARIAL,10,WritableFont.BOLD);56. 57. /*以下设置三种单元格样式,灵活备用*/58. /用于标题居中59. WritableCellFormatwcf_center=newWritableCellFormat(BoldFont);60. wcf_center.setBorder(Border.ALL,BorderLine
7、Style.THIN);/线条61. wcf_center.setVerticalAlignment(VerticalAlignment.CENTRE);/文字垂直对齐62. wcf_center.setAlignment(Alignment.CENTRE);/文字水平对齐63. wcf_center.setWrap(false);/文字是否换行64. 65. /用于正文居左66. WritableCellFormatwcf_left=newWritableCellFormat(NormalFont);67. wcf_left.setBorder(Border.NONE,BorderLineS
8、tyle.THIN);/线条68. wcf_left.setVerticalAlignment(VerticalAlignment.CENTRE);/文字垂直对齐69. wcf_left.setAlignment(Alignment.LEFT);/文字水平对齐70. wcf_left.setWrap(false);/文字是否换行71. 72. 73. /*以下是EXCEL开头大标题,暂时省略*/74. /sheet.mergeCells(0,0,colWidth,0);75. /sheet.addCell(newLabel(0,0,XX报表,wcf_center);76. /*以下是EXCEL
9、第一行列标题*/77. for(inti=0;iTitle.length;i+)78. sheet.addCell(newLabel(i,0,Titlei,wcf_center);79. 80. /*以下是EXCEL正文数据*/81. Fieldfields=null;82. inti=1;83. for(Objectobj:listContent)84. fields=obj.getClass().getDeclaredFields();85. intj=0;86. for(Fieldv:fields)87. v.setAccessible(true);88. Objectva=v.get(
10、obj);89. if(va=null)90. va=;91. 92. sheet.addCell(newLabel(j,i,va.toString(),wcf_left);93. j+;94. 95. i+;96. 97. /*将以上缓存中的内容写到EXCEL文件中*/98. workbook.write();99. /*关闭文件*/100. workbook.close();101. 102. catch(Exceptione)103. result=系统提示:Excel文件导出失败,原因:+e.toString();104. System.out.println(result);105.
11、 e.printStackTrace();106. 107. returnresult;108. 109. 3.通用导出:javaview plaincopy1. packagemon.excel.parser;2. 3. 4. importjava.io.FileOutputStream;5. importjava.io.OutputStream;6. importjava.lang.reflect.Field;7. importjava.lang.reflect.Method;8. importjava.util.ArrayList;9. importjava.util.Collectio
12、n;10. importjava.util.Date;11. importjava.util.HashMap;12. importjava.util.Iterator;13. importjava.util.List;14. importjava.util.Map;15. 16. 17. importorg.apache.poi.hssf.usermodel.HSSFRichTextString;18. importorg.apache.poi.hssf.usermodel.HSSFWorkbook;19. importorg.apache.poi.ss.usermodel.Cell;20.
13、importorg.apache.poi.ss.usermodel.RichTextString;21. importorg.apache.poi.ss.usermodel.Row;22. importorg.apache.poi.ss.usermodel.Sheet;23. importorg.apache.poi.ss.usermodel.Workbook;24. 25. 26. importcom.huateng.test.pojo.Student;27. 28. 29. publicclassExcelExport230. 31. 32. publicstaticvoidexportE
14、xcel(Stringtitle,ClasspojoClass,CollectiondataSet,33. OutputStreamout)34. /使用userModel模式实现的,当excel文档出现10万级别的大数据文件可能导致OOM内存溢出35. exportExcelInUserModel(title,pojoClass,dataSet,out);36. /使用eventModel实现,可以一边读一边处理,效率较高,但是实现复杂,暂时未实现37. 38. privatestaticvoidexportExcelInUserModel(Stringtitle,ClasspojoClas
15、s,CollectiondataSet,39. OutputStreamout)40. try41. /首先检查数据看是否是正确的42. if(dataSet=null|dataSet.size()=0)43. thrownewException(导出数据为空!);44. 45. if(title=null|out=null|pojoClass=null)46. 47. thrownewException(传入参数不能为空!);48. 49. /声明一个工作薄50. Workbookworkbook=newHSSFWorkbook();51. /生成一个表格52. Sheetsheet=wor
16、kbook.createSheet(title);53. 54. 55. /标题56. ListexportFieldTitle=newArrayList();57. ListexportFieldWidth=newArrayList();58. /拿到所有列名,以及导出的字段的get方法59. ListmethodObj=newArrayList();60. MapconvertMethod=newHashMap();61. /得到所有字段62. Fieldfileds=pojoClass.getDeclaredFields();63. /遍历整个filed64. for(inti=0;if
17、ileds.length;i+)65. Fieldfield=filedsi;66. Excelexcel=field.getAnnotation(Excel.class);67. /如果设置了annottion68. if(excel!=null)69. /添加到标题70. exportFieldTitle.add(excel.exportName();71. /添加标题的列宽72. exportFieldWidth.add(excel.exportFieldWidth();73. /添加到需要导出的字段的方法74. Stringfieldname=field.getName();75. /
18、System.out.println(i+列宽+excel.exportName()+excel.exportFieldWidth();76. StringBuffergetMethodName=newStringBuffer(get);77. getMethodName.append(fieldname.substring(0,1)78. .toUpperCase();79. getMethodName.append(fieldname.substring(1);80. 81. 82. MethodgetMethod=pojoClass.getMethod(getMethodName.toS
19、tring(),83. newClass);84. 85. 86. methodObj.add(getMethod);87. if(excel.exportConvertSign()=1)88. 89. StringBuffergetConvertMethodName=newStringBuffer(get);90. getConvertMethodName.append(fieldname.substring(0,1)91. .toUpperCase();92. getConvertMethodName.append(fieldname.substring(1);93. getConvert
20、MethodName.append(Convert);94. /System.out.println(convert:+getConvertMethodName.toString();95. MethodgetConvertMethod=pojoClass.getMethod(getConvertMethodName.toString(),96. newClass);97. convertMethod.put(getMethodName.toString(),getConvertMethod);98. 99. 100. 101. intindex=0;102. /产生表格标题行103. Row
21、row=sheet.createRow(index);104. for(inti=0,exportFieldTitleSize=exportFieldTitle.size();iexportFieldTitleSize;i+)105. Cellcell=row.createCell(i);106. /cell.setCellStyle(style);107. RichTextStringtext=newHSSFRichTextString(108. exportFieldTitle.get(i);109. cell.setCellValue(text);110. 111. 112. 113.
22、/设置每行的列宽114. for(inti=0;iexportFieldWidth.size();i+)115. /256=65280/255116. sheet.setColumnWidth(i,256*exportFieldWidth.get(i);117. 118. Iteratorits=dataSet.iterator();119. /循环插入剩下的集合120. while(its.hasNext()121. /从第二行开始写,第一行是标题122. index+;123. row=sheet.createRow(index);124. Objectt=its.next();125.
23、for(intk=0,methodObjSize=methodObj.size();kmethodObjSize;k+)126. Cellcell=row.createCell(k);127. MethodgetMethod=methodObj.get(k);128. Objectvalue=null;129. if(convertMethod.containsKey(getMethod.getName()130. 131. Methodcm=convertMethod.get(getMethod.getName();132. value=cm.invoke(t,newObject);133.
24、 else134. 135. value=getMethod.invoke(t,newObject);136. 137. cell.setCellValue(value.toString();138. 139. 140. 141. 142. workbook.write(out);143. catch(Exceptione)144. e.printStackTrace();145. 146. 147. 148. 149. 150. 151. publicstaticvoidmain(Stringargs)throwsException152. 153. 154. /构造一个模拟的List来测试
25、,实际使用时,这个集合用从数据库中查出来155. Studentpojo2=newStudent();156. pojo2.setName(第一行数据);157. pojo2.setAge(28);158. pojo2.setSex(2);159. pojo2.setDesc(abcdefghijklmnop);160. pojo2.setBirthDate(newDate();161. pojo2.setIsVip(true);162. Listlist=newArrayList();163. list.add(pojo2);164. for(inti=0;i50000;i+)165. St
26、udentpojo=newStudent();166. pojo.setName(一二三四五六七八九);167. pojo.setAge(22);168. pojo.setSex(1);169. pojo.setDesc(abcdefghijklmnop);170. pojo.setBirthDate(newDate();171. pojo.setIsVip(false);172. list.add(pojo);173. 174. /构造输出对象,可以从response输出,直接向用户提供下载175. OutputStreamout=newFileOutputStream(D:/testOne
27、.xls);176. /开始时间177. Longl=System.currentTimeMillis();178. /注意179. ExcelExport2ex=newExcelExport2();180. /181. ex.exportExcel(测试,Student.class,list,out);182. out.close();183. /结束时间184. Longs=System.currentTimeMillis();185. System.out.println(excel导出成功);186. System.out.println(总共耗时:+(s-l);187. 188. 1
28、89. 190. 191. 192. 4.通用导入:javaview plaincopy1. packagemon.excel.parser;2. 3. 4. importjava.io.File;5. importjava.io.FileInputStream;6. importjava.lang.reflect.Field;7. importjava.lang.reflect.Method;8. importjava.lang.reflect.Type;9. importjava.text.SimpleDateFormat;10. importjava.util.ArrayList;11.
29、 importjava.util.Collection;12. importjava.util.HashMap;13. importjava.util.Iterator;14. importjava.util.List;15. importjava.util.Map;16. 17. 18. importorg.apache.poi.hssf.usermodel.HSSFSheet;19. importorg.apache.poi.hssf.usermodel.HSSFWorkbook;20. importorg.apache.poi.ss.usermodel.Cell;21. importor
30、g.apache.poi.ss.usermodel.Row;22. 23. 24. importcom.huateng.test.pojo.Student;25. 26. 27. publicclassExcelImport228. 29. publicCollectionimportExcel(Filefile,ClasspojoClass,String.pattern)30. 31. Collectiondist=newArrayList();32. try33. /得到目标目标类的所有的字段列表34. Fieldfiled=pojoClass.getDeclaredFields();35
31、. /将所有标有Annotation的字段,也就是允许导入数据的字段,放入到一个map中36. MapfieldSetMap=newHashMap();37. 38. MapfieldSetConvertMap=newHashMap();39. 40. 41. /循环读取所有字段42. for(inti=0;ifiled.length;i+)43. Fieldf=filedi;44. 45. /得到单个字段上的Annotation46. Excelexcel=f.getAnnotation(Excel.class);47. 48. /如果标识了Annotationd的话49. if(excel
32、!=null)50. /构造设置了Annotation的字段的Setter方法51. Stringfieldname=f.getName();52. StringsetMethodName=set53. +fieldname.substring(0,1).toUpperCase()54. +fieldname.substring(1);55. /构造调用的method,56. MethodsetMethod=pojoClass.getMethod(setMethodName,57. newClassf.getType();58. /将这个method以Annotaion的名字为key来存入。5
33、9. 60. /对于重名将导致覆盖失败,对于此处的限制需要61. fieldSetMap.put(excel.exportName(),setMethod);62. 63. if(excel.importConvertSign()=1)64. 65. StringBuffersetConvertMethodName=newStringBuffer(set);66. setConvertMethodName.append(fieldname.substring(0,1)67. .toUpperCase();68. setConvertMethodName.append(fieldname.sub
34、string(1);69. setConvertMethodName.append(Convert);70. MethodgetConvertMethod=pojoClass.getMethod(setConvertMethodName.toString(),71. newClassString.class);72. fieldSetConvertMap.put(excel.exportName(),getConvertMethod);73. 74. 75. 76. 77. 78. 79. 80. 81. 82. /将传入的File构造为FileInputStream;83. FileInpu
35、tStreamin=newFileInputStream(file);84. /得到工作表85. HSSFWorkbookbook=newHSSFWorkbook(in);86. /得到第一页87. HSSFSheetsheet=book.getSheetAt(0);88. /得到第一面的所有行89. Iteratorrow=sheet.rowIterator();90. 91. 92. /得到第一行,也就是标题行93. Rowtitle=row.next();94. /得到第一行的所有列95. IteratorcellTitle=title.cellIterator();96. /将标题的文
36、字内容放入到一个map中。97. Maptitlemap=newHashMap();98. /从标题第一列开始99. inti=0;100. /循环标题所有的列101. while(cellTitle.hasNext()102. Cellcell=cellTitle.next();103. Stringvalue=cell.getStringCellValue();104. titlemap.put(i,value);105. i=i+1;106. 107. 108. 109. /用来格式化日期的DateFormat110. SimpleDateFormatsf;111. if(pattern
37、.length1)112. 113. sf=newSimpleDateFormat(yyyy-MM-dd);114. 115. else116. sf=newSimpleDateFormat(pattern0);117. 118. 119. while(row.hasNext()120. /标题下的第一行121. Rowrown=row.next();122. 123. /行的所有列124. Iteratorcellbody=rown.cellIterator();125. 126. /得到传入类的实例127. ObjecttObject=pojoClass.newInstance();128
38、. 129. intk=0;130. /遍历一行的列131. while(cellbody.hasNext()132. Cellcell=cellbody.next();133. /这里得到此列的对应的标题134. StringtitleString=(String)titlemap.get(k);135. /如果这一列的标题和类中的某一列的Annotation相同,那么则调用此类的的set方法,进行设值136. if(fieldSetMap.containsKey(titleString)137. 138. MethodsetMethod=(Method)fieldSetMap.get(ti
39、tleString);139. /得到setter方法的参数140. Typets=setMethod.getGenericParameterTypes();141. /只要一个参数142. Stringxclass=ts0.toString();143. /判断参数类型144. System.out.println(类型:+xclass);145. 146. if(fieldSetConvertMap.containsKey(titleString)147. 148. 149. fieldSetConvertMap.get(titleString).invoke(tObject,150. cell.getStringCellValue();151. 152. 153. else154. if(xclass.equals(classjava.lang.String)155. setMethod
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- GB/T 45612-2025航空航天用1 100 MPa MJ螺纹花键头螺栓
- 编程培训班汇报
- 交通工程安全生产培训
- 研究生教育与保安专业发展的联系计划
- 车辆过户项目合同协议
- 演出用工协议书
- 车位出租转让合同协议
- 送水店转让合同协议
- 《古代小说选读》课件
- 消防双方协议书
- 大神心理测试题及答案
- 2025春季学期国开河南电大本科《行政管理理论与实践专题讲座》一平台无纸化考试(作业练习+我要考试)试题及答案
- 全球汽车产业发展现状与趋势
- 机械制造质量整改报告范文
- 2025贵州毕节市七星关区招聘城市社区工作者186人笔试备考题库及答案解析
- 山东省泰安市2025届高三二轮模拟检测考试政治(泰安二模)(含答案)
- 2025年特种设备安全考试题库(设备拆除)试题
- 2025-2030中国环境监测发展分析及发展趋势与投资前景研究报告
- 少模掺铒光纤放大器增益均衡与平坦化设计研究
- 大疆精灵4 RTK无人机操作与测绘培训指南
- 2025年陕西延长石油(集团)有限责任公司招聘笔试参考题库含答案解析
评论
0/150
提交评论