综观java读取和创建excel方法

来源:互联网 发布:mac apache 虚拟主机 编辑:程序博客网 时间:2024/05/18 03:15

1. jxl库

jxl.jar库下载地址:http://download.csdn.net/detail/yahohi/3826761

使用方法:

import java.io.FileInputStream;import java.io.InputStream;import jxl.Cell;import jxl.Sheet;import jxl.Workbook;public class xls {public boolean readxlsByjxl(String filepath){Workbook rwb;try{InputStream is = new FileInputStream(filepath);rwb = Workbook.getWorkbook(is);rwb.getNumberOfSheets();Sheet st = rwb.getSheet("Sheet1");int rows = st.getRows();int cols = st.getColumns();System.out.println("table name:"+st.getName());System.out.println("total rows: "+rows);System.out.println("total cols: "+cols);for(int i = 0;i < rows;i ++){Cell c1 = st.getCell(0, i);Cell c2 = st.getCell(1, i);Cell c3 = st.getCell(2, i);Cell c4 = st.getCell(3, i);System.out.println(c1.getContents()+"  "+c2.getContents()+"   "+c3.getContents()+"  "+c4.getContents());}}catch(Exception e){e.printStackTrace();}return true;}public static void main(String[] args) {// TODO Auto-generated method stubxls x = new xls();x.readxlsByjxl("C:/test.xls");}}


2. poi库

poi.jar下载地址:http://download.csdn.net/detail/yahohi/3826817

poi.jar的详细使用文档:http://download.csdn.net/detail/yahohi/3826782

下面介绍和代码引用自http://www.cnblogs.com/dcba1112/archive/2011/06/06/2073952.html

 

Poi 读取文件的例子网上比较多, 但是很多都有小问题,今天我做了一个上传文件并显示XLS内容的模块,

参考了http://www.iteye.com/topic/388005 例程 ,

由于我用的3.7 的版本, 例程里的代码import 用的WorkbookFactory在3.7里已经不存在了,不知道

参考用的那个版本.所有我就使用了hssf和 ss相结合的调用.没有再使用例程方生产方式

例程 Workbook wb = WorkbookFactory.create(is);

我的代码: HSSFWorkbook wb = new HSSFWorkbook(fs);

例程有个漏洞就是为判断cell为空的情况,读取的数据列会自动向前

移动一列.这个问题很验证,我测试了一个下午才发现的.

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;

Java代码
  1. public class SummaryHSSF {
  2. public staticvoid main(String[] args) throws IOException {
  3. //创建Workbook对象(这一个对象代表着对应的一个Excel文件)
  4. //HSSFWorkbook表示以xls为后缀名的文件
  5. Workbook wb = new HSSFWorkbook();
  6. //获得CreationHelper对象,这个应该是一个帮助类
  7. CreationHelper helper = wb.getCreationHelper();
  8. //创建Sheet并给名字(表示Excel的一个Sheet)
  9. Sheet sheet1 = wb.createSheet("HSSF_Sheet_1");
  10. Sheet sheet2 = wb.createSheet("HSSF_Sheet_2");
  11. //Row表示一行Cell表示一列
  12. Row row = null;
  13. Cell cell = null;
  14. for(int i=0;i<60;i=i+2){
  15. //获得这个sheet的第i行
  16. row = sheet1.createRow(i);
  17. //设置行长度自动
  18. //row.setHeight((short)500);
  19. row.setHeightInPoints(20);
  20. //row.setZeroHeight(true);
  21. for(int j=0;j<25;j++){
  22. //设置每个sheet每一行的宽度,自动,根据需求自行确定
  23. sheet1.autoSizeColumn(j+1, true);
  24. //创建一个基本的样式
  25. CellStyle cellStyle = SummaryHSSF.createStyleCell(wb);
  26. //获得这一行的每j列
  27. cell = row.createCell(j);
  28. if(j==0){
  29. //设置文字在单元格里面的位置
  30. cellStyle = SummaryHSSF.setCellStyleAlignment(cellStyle, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER);
  31. //先创建字体样式,并把这个样式加到单元格的字体里面
  32. cellStyle.setFont(createFonts(wb));
  33. //把这个样式加到单元格里面
  34. cell.setCellStyle(cellStyle);
  35. //给单元格设值
  36. cell.setCellValue(true);
  37. }else if(j==1){
  38. //设置文字在单元格里面的位置
  39. cellStyle = SummaryHSSF.setCellStyleAlignment(cellStyle, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER);
  40. //设置这个样式的格式(Format)
  41. cellStyle = SummaryHSSF.setCellFormat(helper,cellStyle, "#,##0.0000");
  42. //先创建字体样式,并把这个样式加到单元格的字体里面
  43. cellStyle.setFont(createFonts(wb));
  44. //把这个样式加到单元格里面
  45. cell.setCellStyle(cellStyle);
  46. //给单元格设值
  47. cell.setCellValue(new Double(2008.2008));
  48. }else if(j==2){
  49. cellStyle = SummaryHSSF.setCellStyleAlignment(cellStyle, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER);
  50. cellStyle.setFont(createFonts(wb));
  51. cell.setCellStyle(cellStyle);
  52. cell.setCellValue(helper.createRichTextString("RichString"+i+j));
  53. }else if(j==3){
  54. cellStyle = SummaryHSSF.setCellStyleAlignment(cellStyle, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER);
  55. cellStyle = SummaryHSSF.setCellFormat(helper,cellStyle, "MM-yyyy-dd");
  56. cell.setCellStyle(cellStyle);
  57. cell.setCellValue(new Date());
  58. }else if(j==24){
  59. cellStyle = SummaryHSSF.setCellStyleAlignment(cellStyle, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER);
  60. cellStyle.setFont(createFonts(wb));
  61. //设置公式
  62. cell.setCellFormula("SUM(E"+(i+1)+":X"+(i+1)+")");
  63. }else{
  64. cellStyle = SummaryHSSF.setCellStyleAlignment(cellStyle, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER);
  65. cellStyle = SummaryHSSF.setFillBackgroundColors(cellStyle,IndexedColors.ORANGE.getIndex(),IndexedColors.ORANGE.getIndex(),CellStyle.SOLID_FOREGROUND);
  66. cell.setCellStyle(cellStyle);
  67. cell.setCellValue(1);
  68. }
  69. }
  70. }
  71. //输出
  72. OutputStream os = new FileOutputStream(new File("c://SummaryHSSF.xls"));
  73. wb.write(os);
  74. os.close();
  75. }
  76. /**
  77. * 边框
  78. * @param wb
  79. * @return
  80. */
  81. public static CellStyle createStyleCell(Workbook wb){
  82. CellStyle cellStyle = wb.createCellStyle();
  83. //设置一个单元格边框颜色
  84. cellStyle.setBorderBottom(CellStyle.BORDER_THIN);
  85. cellStyle.setBorderTop(CellStyle.BORDER_THIN);
  86. cellStyle.setBorderLeft(CellStyle.BORDER_THIN);
  87. cellStyle.setBorderRight(CellStyle.BORDER_THIN);
  88. //设置一个单元格边框颜色
  89. cellStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());
  90. cellStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());
  91. cellStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());
  92. cellStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());
  93. return cellStyle;
  94. }
  95. /**
  96. * 设置文字在单元格里面的位置
  97. * CellStyle.ALIGN_CENTER
  98. * CellStyle.VERTICAL_CENTER
  99. * @param cellStyle
  100. * @param halign
  101. * @param valign
  102. * @return
  103. */
  104. public static CellStyle setCellStyleAlignment(CellStyle cellStyle,short halign,short valign){
  105. //设置上下
  106. cellStyle.setAlignment(CellStyle.ALIGN_CENTER);
  107. //设置左右
  108. cellStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
  109. return cellStyle;
  110. }
  111. /**
  112. * 格式化单元格
  113. * 如#,##0.00,m/d/yy去HSSFDataFormat或XSSFDataFormat里面找
  114. * @param cellStyle
  115. * @param fmt
  116. * @return
  117. */
  118. public static CellStyle setCellFormat(CreationHelper helper,CellStyle cellStyle,String fmt){
  119. //还可以用其它方法创建format
  120. cellStyle.setDataFormat(helper.createDataFormat().getFormat(fmt));
  121. return cellStyle;
  122. }
  123. /**
  124. * 前景和背景填充的着色
  125. * @param cellStyle
  126. * @param bg IndexedColors.ORANGE.getIndex();
  127. * @param fg IndexedColors.ORANGE.getIndex();
  128. * @param fp CellStyle.SOLID_FOREGROUND
  129. * @return
  130. */
  131. public static CellStyle setFillBackgroundColors(CellStyle cellStyle,short bg,short fg,short fp){
  132. //cellStyle.setFillBackgroundColor(bg);
  133. cellStyle.setFillForegroundColor(fg);
  134. cellStyle.setFillPattern(fp);
  135. return cellStyle;
  136. }
  137. /**
  138. * 设置字体
  139. * @param wb
  140. * @return
  141. */
  142. public static Font createFonts(Workbook wb){
  143. //创建Font对象
  144. Font font = wb.createFont();
  145. //设置字体
  146. font.setFontName("黑体");
  147. //着色
  148. font.setColor(HSSFColor.BLUE.index);
  149. //斜体
  150. font.setItalic(true);
  151. //字体大小
  152. font.setFontHeight((short)300);
  153. return font;
  154. }
  155. }


读取Excel文件

Java代码
  1. public class ReadExcel {
  2. public staticvoid main(String[] args) throws Exception {
  3. InputStream is = new FileInputStream(new File("c://SummaryHSSF.xls"));
  4. //根据输入流创建Workbook对象
  5. Workbook wb = WorkbookFactory.create(is);
  6. //HSSFWorkbook wb = new HSSFWorkbook(is);
  7. //get到Sheet对象
  8. Sheet sheet = wb.getSheetAt(0);
  9. //这个必须用接口
  10. for(Row row : sheet){
  11. for(Cell cell : row){
  12. //实际读取中这里需要判断为空的情况
  13. //if(cell == null){
  14. //空处理
  15. //}
  16. //cell.getCellType是获得cell里面保存的值的type
  17. //如Cell.CELL_TYPE_STRING
  18. switch(cell.getCellType()){
  19. case Cell.CELL_TYPE_BOOLEAN:
  20. //得到Boolean对象的方法
  21. System.out.print(cell.getBooleanCellValue()+" ");
  22. break;
  23. case Cell.CELL_TYPE_NUMERIC:
  24. //先看是否是日期格式
  25. if(DateUtil.isCellDateFormatted(cell)){
  26. //读取日期格式
  27. System.out.print(cell.getDateCellValue()+" ");
  28. }else{
  29. //读取数字
  30. System.out.print(cell.getNumericCellValue()+" ");
  31. }
  32. break;
  33. case Cell.CELL_TYPE_FORMULA:
  34. //读取公式
  35. System.out.print(cell.getCellFormula()+" ");
  36. break;
  37. case Cell.CELL_TYPE_STRING:
  38. //读取String
  39. System.out.print(cell.getRichStringCellValue().toString()+" ");
  40. break;
  41. }
  42. }
  43. System.out.println("");
  44. }
  45. }
  46. }



还有一种传统的读法

Java代码
  1. Sheet sheet = wb.getSheetAt(0);
  2. for (Iterator rit = sheet.rowIterator(); rit.hasNext(); ) {
  3. Row row = (Row)rit.next();
  4. for (Iterator cit = row.cellIterator(); cit.hasNext(); ) {
  5. Cell cell = (Cell)cit.next();
  6. // Do something here
  7. }
  8. }
  9. HSSFSheet sheet = wb.getSheetAt(0);
  10. for (Iterator<HSSFRow> rit = (Iterator<HSSFRow>)sheet.rowIterator(); rit.hasNext(); ) {
  11. HSSFRow row = rit.next();
  12. for (Iterator<HSSFCell> cit = (Iterator<HSSFCell>)row.cellIterator(); cit.hasNext(); ) {
  13. HSSFCell cell = cit.next();
  14. // Do something here
  15. }
  16. }

仅供参考,谢谢。

原创粉丝点击