Java 操作 Excel (读取Excel2003 2007,Poi实现)

原文地址:
一. Apache POI 简介( http://poi.apache.org/)

使用Java程序读写Microsoft Office,提供了下面这几种类型:

HSSF-提供读写Microsoft Excel XLS格式档案的功能。
XSSF-提供读写Microsoft Excel OOXML XLSX格式档案的功能。
HWPF-提供读写Microsoft Word DOC格式档案的功能。
HSLF- 供读写Microsoft PowerPoint格式档案的功能。
HDGF-提供读Microsoft Visio格式档案的功能。
HPBF-提供读Microsoft Publisher格式档案的功能。


二、POI操作Excel


1. 官方快速帮助:http://poi.apache.org/spreadsheet/quick-guide.html

2. 导入包:poi-3.6.jar


参考:



1. http://www.blogjava.net/vwpolo/archive/2009/09/16/295243.html

2. http://hacker-zxf.iteye.com/blog/746546

3. http://zmx.iteye.com/blog/622536

4. http://canfly2010.iteye.com/blog/701726
5. http://blog.youkuaiyun.com/aerchi
Java代码 收藏代码
  1. packageexcel.poi;
  2. importjava.io.File;
  3. importjava.io.FileInputStream;
  4. importjava.io.FileOutputStream;
  5. importjava.io.IOException;
  6. importjava.io.InputStream;
  7. importjava.util.Date;
  8. importjava.util.Iterator;
  9. importorg.apache.poi.POITextExtractor;
  10. importorg.apache.poi.extractor.ExtractorFactory;
  11. importorg.apache.poi.hssf.usermodel.HSSFCell;
  12. importorg.apache.poi.hssf.usermodel.HSSFCellStyle;
  13. importorg.apache.poi.hssf.usermodel.HSSFDataFormat;
  14. importorg.apache.poi.hssf.usermodel.HSSFRow;
  15. importorg.apache.poi.hssf.usermodel.HSSFSheet;
  16. importorg.apache.poi.hssf.usermodel.HSSFWorkbook;
  17. importorg.apache.poi.openxml4j.exceptions.InvalidFormatException;
  18. importorg.apache.poi.openxml4j.exceptions.OpenXML4JException;
  19. importorg.apache.poi.poifs.filesystem.POIFSFileSystem;
  20. importorg.apache.poi.ss.usermodel.IndexedColors;
  21. importorg.apache.poi.xssf.usermodel.XSSFCell;
  22. importorg.apache.poi.xssf.usermodel.XSSFCellStyle;
  23. importorg.apache.poi.xssf.usermodel.XSSFCreationHelper;
  24. importorg.apache.poi.xssf.usermodel.XSSFRow;
  25. importorg.apache.poi.xssf.usermodel.XSSFSheet;
  26. importorg.apache.poi.xssf.usermodel.XSSFWorkbook;
  27. importorg.apache.xmlbeans.XmlException;
  28. publicclassReadExcel{
  29. /**
  30. *读取office2003xls
  31. *@paramfilePath
  32. */
  33. @SuppressWarnings({"unchecked","deprecation"})
  34. publicvoidloadXls(StringfilePath){
  35. try{
  36. InputStreaminput=newFileInputStream("D:\\aerchi\\test\\xls\\流量.xls");
  37. POIFSFileSystemfs=newPOIFSFileSystem(input);
  38. HSSFWorkbookwb=newHSSFWorkbook(fs);
  39. HSSFSheetsheet=wb.getSheetAt(0);
  40. //Iterateovereachrowinthesheet
  41. Iteratorrows=sheet.rowIterator();
  42. while(rows.hasNext()){
  43. HSSFRowrow=(HSSFRow)rows.next();
  44. System.out.println("Row#"+row.getRowNum());
  45. //Iterateovereachcellintherowandprintoutthecell"s
  46. //content
  47. Iteratorcells=row.cellIterator();
  48. while(cells.hasNext()){
  49. HSSFCellcell=(HSSFCell)cells.next();
  50. System.out.println("Cell#"+cell.getCellNum());
  51. switch(cell.getCellType()){
  52. caseHSSFCell.CELL_TYPE_NUMERIC:
  53. System.out.println(cell.getNumericCellValue());
  54. break;
  55. caseHSSFCell.CELL_TYPE_STRING:
  56. System.out.println(cell.getStringCellValue());
  57. break;
  58. caseHSSFCell.CELL_TYPE_BOOLEAN:
  59. System.out.println(cell.getBooleanCellValue());
  60. break;
  61. caseHSSFCell.CELL_TYPE_FORMULA:
  62. System.out.println(cell.getCellFormula());
  63. break;
  64. default:
  65. System.out.println("unsuportedselltype");
  66. break;
  67. }
  68. }
  69. }
  70. }catch(IOExceptionex){
  71. ex.printStackTrace();
  72. }
  73. }
  74. /**
  75. *读取xlsx文本
  76. *@paramfilePath
  77. */
  78. publicvoidloadXlsxText(StringfilePath){
  79. FileinputFile=newFile("D:\\aerchi.xlsx");
  80. try{
  81. POITextExtractorextractor=ExtractorFactory.createExtractor(inputFile);
  82. System.out.println(extractor.getText());
  83. }catch(InvalidFormatExceptione){
  84. e.printStackTrace();
  85. }catch(IOExceptione){
  86. e.printStackTrace();
  87. }catch(OpenXML4JExceptione){
  88. e.printStackTrace();
  89. }catch(XmlExceptione){
  90. e.printStackTrace();
  91. }
  92. }
  93. /**
  94. *读取office2007xlsx
  95. *@paramfilePath
  96. */
  97. publicvoidloadXlsx(StringfilePath){
  98. //构造XSSFWorkbook对象,strPath传入文件路径
  99. XSSFWorkbookxwb=null;
  100. try{
  101. xwb=newXSSFWorkbook("D:\\aerchi.xlsx");
  102. }catch(IOExceptione){
  103. System.out.println("读取文件出错");
  104. e.printStackTrace();
  105. }
  106. //读取第一章表格内容
  107. XSSFSheetsheet=xwb.getSheetAt(0);
  108. //定义row、cell
  109. XSSFRowrow;
  110. Stringcell;
  111. //循环输出表格中的内容
  112. for(inti=sheet.getFirstRowNum()+1;i<sheet.getPhysicalNumberOfRows();i++){
  113. row=sheet.getRow(i);
  114. for(intj=row.getFirstCellNum();j<row.getPhysicalNumberOfCells();j++){
  115. //通过row.getCell(j).toString()获取单元格内容,
  116. if(j==1&&i!=0){
  117. cell=row.getCell(j).getDateCellValue().toLocaleString();
  118. }else{
  119. cell=row.getCell(j).toString();
  120. }
  121. /*//获取字体和背景颜色
  122. StringrgbShort=row.getCell(j).getCellStyle().getFont().getCTFont().getColorArray()[0].xmlText();
  123. rgbShort=ReadExcel.substringBetween(rgbShort,"rgb=\"","\"/>");
  124. StringrgbShort=row.getCell(j).getCellStyle().getFillBackgroundXSSFColor().getCTColor().toString();
  125. Colorcolor=newColor(Color.BLUE.getRGB());
  126. System.out.print(cell+",index:"+rgbShort+"red:"+color.getRed()+"blue:"+color.getBlue()+"\t");*/
  127. System.out.print(cell+"\t");
  128. }
  129. System.out.println("");
  130. }
  131. }
  132. /**
  133. *HSSF写入excelxls格式
  134. *@paramfilePath
  135. *@throwsIOException
  136. */
  137. publicvoidwriteXls(StringfilePath)throwsIOException{
  138. //工作簿23.
  139. HSSFWorkbookhssfworkbook=newHSSFWorkbook();
  140. //创建sheet页25.
  141. HSSFSheethssfsheet=hssfworkbook.createSheet();
  142. //sheet名称
  143. hssfworkbook.setSheetName(0,"研发部门");
  144. //取得第一行29.
  145. HSSFRowhssfrow=hssfsheet.createRow(0);
  146. //创建第一个单元格并处理乱码31.
  147. HSSFCellhssfcell_0=hssfrow.createCell((short)0);
  148. //hssfcell_0.setEncoding(HSSFWorkbook.ENCODING_UTF_16);
  149. //对第一个单元格赋值34.
  150. hssfcell_0.setCellValue("研发工程师1");
  151. //日期单元格格式处理
  152. HSSFCellStylehssfcellstyle=hssfworkbook.createCellStyle();
  153. //m/d/yyh:mm39.
  154. hssfcellstyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy"));
  155. //创建第二个单元格41.
  156. HSSFCellhssfcell_1=hssfrow.createCell((short)1);
  157. hssfcell_1.setCellValue(newDate());
  158. hssfcell_1.setCellStyle(hssfcellstyle);
  159. hssfrow.createCell((short)2).setCellValue(true);
  160. hssfrow.createCell((short)3).setCellValue(122.00);
  161. //输出49.
  162. FileOutputStreamfileoutputstream=newFileOutputStream("d:\\exceltext.xls");
  163. hssfworkbook.write(fileoutputstream);
  164. fileoutputstream.close();
  165. }
  166. @SuppressWarnings("static-access")
  167. publicvoidwriteXlsx(StringfilePath)throwsIOException{
  168. //工作簿
  169. XSSFWorkbookhssfworkbook=newXSSFWorkbook();
  170. //获得CreationHelper对象,这个应该是一个帮助类
  171. XSSFCreationHelperhelper=hssfworkbook.getCreationHelper();
  172. //创建sheet页
  173. XSSFSheethssfsheet=hssfworkbook.createSheet();
  174. //设置sheet名称
  175. hssfworkbook.setSheetName(0,"我的测试sheet");
  176. //取得第一行
  177. XSSFRowfirstRow=hssfsheet.createRow(0);
  178. //创建第一个单元格
  179. XSSFCellhssfcell_0=firstRow.createCell(0);
  180. //hssfcell_0.setEncoding(HSSFWorkbook.ENCODING_UTF_16);并处理乱码
  181. //对第一个单元格赋值
  182. hssfcell_0.setCellValue("名称");
  183. //创建第二个单元格
  184. XSSFCellhssfcell_1=firstRow.createCell(1);
  185. hssfcell_1.setCellValue("创建日期");
  186. //日期单元格格式处理
  187. XSSFCellStyledateCellStyle=hssfworkbook.createCellStyle();
  188. //m/d/yyh:mm设置日期格式
  189. dateCellStyle.setDataFormat(helper.createDataFormat().getFormat("yyyy-MM-ddhh:mm:ss"));
  190. dateCellStyle=ReadExcel.setFillBackgroundColors(dateCellStyle,IndexedColors.BLACK.getIndex(),IndexedColors.YELLOW.getIndex(),dateCellStyle.SOLID_FOREGROUND);
  191. //设置其他标题
  192. firstRow.createCell(2).setCellValue("用户");
  193. firstRow.createCell(3).setCellValue("备注");
  194. //写入所有内容行
  195. for(introwInt=1;rowInt<10;rowInt++){
  196. XSSFRowrow=hssfsheet.createRow(rowInt);
  197. XSSFCellcell_0=row.createCell(0);
  198. cell_0.setCellValue("碌人乘凉");
  199. XSSFCellcell_1=row.createCell(1);
  200. cell_1.setCellValue(newDate());
  201. cell_1.setCellStyle(dateCellStyle);
  202. XSSFCellcell_2=row.createCell(2);
  203. cell_2.setCellValue("超级会员");
  204. XSSFCellcell_3=row.createCell(3);
  205. cell_3.setCellValue("这里是备注信息");
  206. }
  207. //输出49.
  208. FileOutputStreamfileoutputstream=newFileOutputStream("d:\\exceltext.xlsx");
  209. hssfworkbook.write(fileoutputstream);
  210. fileoutputstream.close();
  211. }
  212. /**
  213. *前景和背景填充的着色
  214. *@paramcellStyle
  215. *@parambgIndexedColors.ORANGE.getIndex();
  216. *@paramfgIndexedColors.ORANGE.getIndex();
  217. *@paramfpCellStyle.SOLID_FOREGROUND
  218. *@return
  219. */
  220. publicstaticXSSFCellStylesetFillBackgroundColors(XSSFCellStylecellStyle,shortbg,shortfg,shortfp){
  221. cellStyle.setFillBackgroundColor(bg);
  222. cellStyle.setFillForegroundColor(fg);
  223. cellStyle.setFillPattern(fp);
  224. returncellStyle;
  225. }
  226. publicstaticvoidmain(String[]args){
  227. ReadExcelreadExcel=newReadExcel();
  228. /*try{
  229. readExcel.writeXlsx("");
  230. }catch(IOExceptione){
  231. e.printStackTrace();
  232. }*/
  233. readExcel.loadXls("");
  234. }
  235. }
<wbr></wbr>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值