jxl操作excel

更新时间:2023-03-08 08:22:28 阅读量: 综合文库 文档下载

说明:文章内容仅供预览,部分内容可能不全。下载后的文档,内容与下面显示的完全一致。下载之前请确认下面内容是否您想要的,是否完整无缺。

用jxl读取excel的数据,由于excel数据在录入时的各种原因,数据后面都有空格,而且读出来以后(也许是编码原因),数据口面不是出 现\就是出现一个不知所谓的乱码符,不要考虑用替换,因为替换只有在你的项目编码方式和内存中excel数据编码方式一样的时候才能替换,否则你连保 存都会提示编码问题而保存不了。

直接用subSequence(0, cellContent.length()-1) 就可以了

同时提醒一下,读取出来的数据时Cell类型的话,直接getContent是可以得到内容的,但具体内容最好依靠下面的方法获 Java代码

1. if (cell.getType() == CellType.LABEL) {

2. LabelCell labelCell = (LabelCell) cell; 3. String cellContent = labelCell.getString();

4. cellContent = (String) cellContent.subSequence(0, cellContent.length()-1);

5. column_contents[cols] = cellContent; 6. }else

7. if (cell.getType() == CellType.NUMBER) {

8. //number的话不用去空格就可以,我测试是这样 9. NumberCell numberCell = (NumberCell) cell; 10. String cellContent = numberCell.getContents(); 11. column_contents[cols] = cellContent; 12.}else

13.if (cell.getType() == CellType.DATE) { 14. DateCell dateCell = (DateCell) cell; 15. Date dateDemo = dateCell.getDate();

16. String cellContent = dateDemo.toString(); 17. column_contents[cols] = cellContent; 18.}

package com.study.poi;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream;

import java.text.DecimalFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFDateUtil; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.study.entity.Emp;

public class PoiExcelTest {

public static void main(String[] args) { Class[] clazz=new

Class[]{Integer.class,String.class,String.class,Integer.class,Date.class,Double.class,Double.class,Integer.class}; List list=null;

DecimalFormat df=new DecimalFormat(\ try {

list = readExcel(\ } catch (ParseException e) { e.printStackTrace(); }

for (Iterator iter=list.iterator(); iter.hasNext();) { Emp emp=iter.next();

System.out.println(\e()+\ew

SimpleDateFormat(\Deptno());

} }

private static int version2003=2003; private static int version2007=2003; private static int version=version2003; private static Workbook wb; private static Sheet sheet; private static Row row; private static Cell cell;

public static List readExcel(String excelFilePath,Class[] clazz) throws ParseException{

List list=new ArrayList(); Emp emp;

version=(excelFilePath.endsWith(\07);

if(version==2003){ try {

InputStream stream=new FileInputStream(new File(excelFilePath));

wb=new HSSFWorkbook(stream); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }

}else if(version==2007){ try {

wb=new XSSFWorkbook(excelFilePath); } catch (IOException e) { e.printStackTrace(); } }

sheet=wb.getSheetAt(0);

int rows=sheet.getLastRowNum();

int cells=sheet.getRow(0).getPhysicalNumberOfCells(); for (int i = 0; i < rows; i++) { row=sheet.getRow(i+1); emp=new Emp();

for (int j = 0; j < cells; j++) { cell=row.getCell(j);

Object obj=getCellValue(cell, clazz[j]); switch (j) { case 0:

emp.setEmpno((Integer)obj);

break; case 1:

emp.setEname((String)obj); break; case 2:

emp.setJob((String)obj); break; case 3:

emp.setMgr((Integer)obj); break; case 4:

emp.setHiredate(new

SimpleDateFormat(\ break; case 5:

emp.setSal((Double)obj); break; case 6:

emp.setComm((Double)obj); break; case 7:

emp.setDeptno((Integer)obj); break; default: break; } }

list.add(emp); }

return list; }

public static Object getCellValue(Cell cell,Class clazz){ String name=clazz.getSimpleName(); if(\

return cell.getStringCellValue();

}else if(\ try {

double valued=cell.getNumericCellValue(); return valued;

} catch (Exception e) { return 0.0; }

}else if(\

try {

int valuei=(int)cell.getNumericCellValue(); return valuei;

} catch (Exception e) { return 0; }

}else if(\

if(HSSFDateUtil.isCellDateFormatted(cell)){ Date date=cell.getDateCellValue(); if(date==null){ return new

SimpleDateFormat(\ }else{

return new

SimpleDateFormat(\ } } }

return null; } }

1. public class SummaryHSSF { 2.

3. public static void main(String[] args) throws IOException {

4. //创建Workbook对象(这一个对象代表着对应的一个Excel文件)

5. //HSSFWorkbook表示以xls为后缀名的文件 6. Workbook wb = new HSSFWorkbook();

7. //获得CreationHelper对象,这个应该是一个帮助类 8. CreationHelper helper = wb.getCreationHelper(); 9. //创建Sheet并给名字(表示Excel的一个Sheet)

10. Sheet sheet1 = wb.createSheet(\11. Sheet sheet2 = wb.createSheet(\12. //Row表示一行Cell表示一列 13. Row row = null; 14. Cell cell = null;

15. for(int i=0;i<60;i=i+2){ 16. //获得这个sheet的第i行 17. row = sheet1.createRow(i); 18. //设置行长度自动 19. //row.setHeight((short)500); 20. row.setHeightInPoints(20); 21. //row.setZeroHeight(true); 22. for(int j=0;j<25;j++){

23. //设置每个sheet每一行的宽度,自动,根据需求自行确定

24. sheet1.autoSizeColumn(j+1, true); 25. //创建一个基本的样式

26. CellStyle cellStyle = SummaryHSSF.createStyleCell(wb);

27. //获得这一行的每j列

28. cell = row.createCell(j); 29. if(j==0){

30. //设置文字在单元格里面的位置

31. cellStyle = SummaryHSSF.setCellStyleAlignment(cellStyle, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER);

32. //先创建字体样式,并把这个样式加到单元格的字体里面

33. cellStyle.setFont(createFonts(wb)); 34. //把这个样式加到单元格里面

35. cell.setCellStyle(cellStyle);

36. //给单元格设值

37. cell.setCellValue(true); 38. }else if(j==1){

39. //设置文字在单元格里面的位置

40. cellStyle = SummaryHSSF.setCellStyleAlignment(cellStyle, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER);

41. //设置这个样式的格式(Format)

42. cellStyle = SummaryHSSF.setCellFormat(helper,cellStyle, \

43. //先创建字体样式,并把这个样式加到单元格的字体里面

44. cellStyle.setFont(createFonts(wb)); 45. //把这个样式加到单元格里面 46. cell.setCellStyle(cellStyle); 47. //给单元格设值

48. cell.setCellValue(new Double(2008.2008));

49. }else if(j==2){

50. cellStyle = SummaryHSSF.setCellStyleAlignment(cellStyle, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER);

51. cellStyle.setFont(createFonts(wb)); 52. cell.setCellStyle(cellStyle);

53. cell.setCellValue(helper.createRichTextString(\54. }else if(j==3){

55. cellStyle = SummaryHSSF.setCellStyleAlignment(cellStyle, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER);

56. cellStyle = SummaryHSSF.setCellFormat(helper,cellStyle, \

57. cell.setCellStyle(cellStyle); 58. cell.setCellValue(new Date()); 59. }else if(j==24){

60. cellStyle = SummaryHSSF.setCellStyleAlignment(cellStyle, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER);

61. cellStyle.setFont(createFonts(wb)); 62. //设置公式

63. cell.setCellFormula(\)+\

64. }else{

65. cellStyle = SummaryHSSF.setCellStyleAlignment(cellStyle, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER);

66. cellStyle = SummaryHSSF.setFillBackgroundColors(cellStyle,IndexedColors.ORANGE.getIndex(),IndexedColors.ORANGE.getIndex(),CellStyle.SOLID_FOREGROUND);

67. cell.setCellStyle(cellStyle); 68. cell.setCellValue(1); 69. } 70. } 71. }

72. //输出

73. OutputStream os = new FileOutputStream(new File(\mmaryHSSF.xls\74. wb.write(os); 75. os.close(); 76. } 77. /** 78. * 边框

79. * @param wb 80. * @return 81. */

82. public static CellStyle createStyleCell(Workbook wb){ 83. CellStyle cellStyle = wb.createCellStyle(); 84. //设置一个单元格边框颜色

85. cellStyle.setBorderBottom(CellStyle.BORDER_THIN); 86. cellStyle.setBorderTop(CellStyle.BORDER_THIN); 87. cellStyle.setBorderLeft(CellStyle.BORDER_THIN); 88. cellStyle.setBorderRight(CellStyle.BORDER_THIN); 89. //设置一个单元格边框颜色

90. cellStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());

91. cellStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());

92. cellStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());

93. cellStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());

94. return cellStyle; 95. } 96. /**

97. * 设置文字在单元格里面的位置 98. * CellStyle.ALIGN_CENTER 99. * CellStyle.VERTICAL_CENTER 100. * @param cellStyle 101. * @param halign 102. * @param valign 103. * @return 104. */

105. public static CellStyle setCellStyleAlignment(CellStyle cellStyle,short halign,short valign){ 106. //设置上下

107. cellStyle.setAlignment(CellStyle.ALIGN_CENTER); 108. //设置左右

109. cellStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);

110. return cellStyle; 111. } 112. /**

113. * 格式化单元格

114. * 如#,##0.00,m/d/yy去HSSFDataFormat或XSSFDataFormat里面找

115. * @param cellStyle

116. * @param fmt 117. * @return 118. */

119. public static CellStyle setCellFormat(CreationHelper helper,CellStyle cellStyle,String fmt){ 120. //还可以用其它方法创建format

121. cellStyle.setDataFormat(helper.createDataFormat().getFormat(fmt));

122. return cellStyle; 123. } 124. /**

125. * 前景和背景填充的着色 126. * @param cellStyle

127. * @param bg IndexedColors.ORANGE.getIndex(); 128. * @param fg IndexedColors.ORANGE.getIndex(); 129. * @param fp CellStyle.SOLID_FOREGROUND 130. * @return 131. */

132. public static CellStyle setFillBackgroundColors(CellStyle cellStyle,short bg,short fg,short fp){

133. //cellStyle.setFillBackgroundColor(bg); 134. cellStyle.setFillForegroundColor(fg); 135. cellStyle.setFillPattern(fp); 136. return cellStyle; 137. } 138. /**

139. * 设置字体 140. * @param wb 141. * @return 142. */

143. public static Font createFonts(Workbook wb){ 144. //创建Font对象

145. Font font = wb.createFont(); 146. //设置字体

147. font.setFontName(\黑体\148. //着色

149. font.setColor(HSSFColor.BLUE.index); 150. //斜体

151. font.setItalic(true); 152. //字体大小

153. font.setFontHeight((short)300); 154. return font; 155. } 156. }

读取Excel文件 Java代码

1. public class ReadExcel {

2. public static void main(String[] args) throws Exception { 3. InputStream is = new FileInputStream(new File(\aryHSSF.xls\

4. //根据输入流创建Workbook对象

5. Workbook wb = WorkbookFactory.create(is); 6. //get到Sheet对象

7. Sheet sheet = wb.getSheetAt(0); 8. //这个必须用接口

9. for(Row row : sheet){ 10. for(Cell cell : row){

11. //cell.getCellType是获得cell里面保存的值的type

12. //如Cell.CELL_TYPE_STRING 13. switch(cell.getCellType()){

14. case Cell.CELL_TYPE_BOOLEAN: 15. //得到Boolean对象的方法

16. System.out.print(cell.getBooleanCellValue()+\

17. break;

18. case Cell.CELL_TYPE_NUMERIC: 19. //先看是否是日期格式

20. if(DateUtil.isCellDateFormatted(cell)){

21. //读取日期格式

22. System.out.print(cell.getDateCellValue()+\

23. }else{

24. //读取数字

25. System.out.print(cell.getNumericCellValue()+\

26. }

27. break;

28. case Cell.CELL_TYPE_FORMULA: 29. //读取公式

30. System.out.print(cell.getCellFormula()+\

31. break;

32. case Cell.CELL_TYPE_STRING: 33. //读取String

34. System.out.print(cell.getRichStringCellValue().toString()+\

35. break; 36. } 37. }

38. System.out.println(\39. } 40. } 41.}

还有一种传统的读法 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 rit = (Iterator)sheet.rowIterator(); rit.hasNext(); ) {

11. HSSFRow row = rit.next();

12. for (Iterator cit = (Iterator)row.cellIterator(); cit.hasNext(); ) {

13. HSSFCell cell = cit.next(); 14. // Do something here 15. } 16. }

1.jxl 生成报表

Java代码

1. package excel; 2.

3. import java.io.FileOutputStream; 4. import java.io.OutputStream;

5. import java.text.SimpleDateFormat; 6. import java.util.Date; 7.

8. import jxl.Workbook;

9. import jxl.format.Alignment; 10.import jxl.format.Border;

11.import jxl.format.BorderLineStyle; 12.import jxl.format.CellFormat; 13.import jxl.write.Label;

14.import jxl.write.WritableCellFormat; 15.import jxl.write.WritableFont; 16.import jxl.write.WritableSheet; 17.import jxl.write.WritableWorkbook;

18./*********************************************************************** 19. *

20. * jxlCreate.java

21. * @copyright Copyright: 2009-2012 22. * @creator 周辉

23. * @create-time Mar 9, 2010 1:35:19 PM 24. * @revision $Id: *

25. ***********************************************************************/

26.public class jxlCreate { 27.

28. /**

29. * @param args 30. */

31. public static void main(String[] args) { 32. // 准备设置excel工作表的标题

33. String[] title = {\编号\产品名称\产品价格\产品数量\生产日期\产地\是否出口\34. try {

35. // 获得开始时间

36. long start = System.currentTimeMillis();

37. // 输出的excel的路径

38. String filePath = \39. // 创建Excel工作薄 40. WritableWorkbook wwb;

41. // 新建立一个jxl文件,即在C盘下生成test.xls 42. OutputStream os = new FileOutputStream(filePath);

43. wwb=Workbook.createWorkbook(os);

44. // 添加第一个工作表并设置第一个Sheet的名字 45. WritableSheet sheet = wwb.createSheet(\产品清单\

46. Label label;

47. for(int i=0;i

48. // Label(x,y,z)其中x代表单元格的第x+1列,第y+1行, 单元格的内容是y

49. // 在Label对象的子对象中指明单元格的位置和内容

50. label = new Label(i,0,title[i]); 51. // 将定义好的单元格添加到工作表中 52. sheet.addCell(label); 53. }

54. // 下面是填充数据 55. /*

56. * 保存数字到单元格,需要使用jxl.write.Number 57. * 必须使用其完整路径,否则会出现错误 58. * */

59. // 填充产品编号

60. jxl.write.Number number = new jxl.write.Number(0,1,20071001);

61. sheet.addCell(number); 62. // 填充产品名称

63. label = new Label(1,1,\金鸽瓜子\64. sheet.addCell(label); 65. /*

66. * 定义对于显示金额的公共格式 67. * jxl会自动实现四舍五入

68. * 例如 2.456会被格式化为2.46,2.454会被格式化为2.45

69. * */

70. jxl.write.NumberFormat nf = new jxl.write.NumberFormat(\

71. jxl.write.WritableCellFormat wcf = new jxl.write.WritableCellFormat(nf);

72. // 填充产品价格

73. jxl.write.Number nb = new jxl.write.Number(2,1,2.45,wcf);

74. sheet.addCell(nb); 75. // 填充产品数量

76. jxl.write.Number numb = new jxl.write.Number(3,1,200);

77. sheet.addCell(numb); 78. /*

79. * 定义显示日期的公共格式 80. * 如:yyyy-MM-dd hh:mm 81. * */

82. SimpleDateFormat sdf = new SimpleDateFormat(\M-dd\

83. String newdate = sdf.format(new Date()); 84. // 填充出产日期

85. label = new Label(4,1,newdate); 86. sheet.addCell(label); 87. // 填充产地

88. label = new Label(5,1,\陕西西安\89. sheet.addCell(label); 90. /*

91. * 显示布尔值 92. * */

93. jxl.write.Boolean bool = new jxl.write.Boolean(6,1,true);

94. sheet.addCell(bool); 95. /*

96. * 合并单元格 97. * 通过

writablesheet.mergeCells(int x,int y,int m,int n);来实现的 98. * 表示将从第x+1列,y+1行到m+1列,n+1行合并 99. *

100. * */

101. sheet.mergeCells(0,3,2,3);

102. label = new Label(0,3,\合并了三个单元格\

103. sheet.addCell(label); 104. /* 105. *

106. * 定义公共字体格式

107. * 通过获取一个字体的样式来作为模板

108. * 首先通过web.getSheet(0)获得第一个sheet 109. * 然后取得第一个sheet的第二列,第一行也就是\产品名称\的字体

110. * */

111. CellFormat cf = wwb.getSheet(0).getCell(1, 0).getCellFormat();

112. WritableCellFormat wc = new WritableCellFormat();

113. // 设置居中

114. wc.setAlignment(Alignment.CENTRE); 115. // 设置边框线

116. wc.setBorder(Border.ALL, BorderLineStyle.THIN);

117. // 设置单元格的背景颜色

118. wc.setBackground(jxl.format.Colour.RED); 119. label = new Label(1,5,\字体\120. sheet.addCell(label); 121.

122. // 设置字体

123. jxl.write.WritableFont wfont = new jxl.write.WritableFont(WritableFont.createFont(\隶书\

124. WritableCellFormat font = new WritableCellFormat(wfont);

125. label = new Label(2,6,\隶书\126. sheet.addCell(label); 127.

128. // 写入数据 129. wwb.write(); 130. // 关闭文件 131. wwb.close();

132. long end = System.currentTimeMillis(); 133. System.out.println(\完成该操作共用的时间是:\

134. } catch (Exception e) {

135. System.out.println(\出现异常---\136. e.printStackTrace(); 137. } 138.

139. } 140. 141. } 2.POI 生成

Java代码

1. package excel; 2.

3. import java.io.FileOutputStream; 4. import java.text.SimpleDateFormat; 5. import java.util.Date; 6.

7. import org.apache.poi.hssf.usermodel.HSSFWorkbook; 8. import org.apache.poi.ss.usermodel.Cell;

9. import org.apache.poi.ss.usermodel.CellStyle; 10.import org.apache.poi.ss.usermodel.DataFormat; 11.import org.apache.poi.ss.usermodel.Row; 12.import org.apache.poi.ss.usermodel.Sheet; 13.import org.apache.poi.ss.usermodel.Workbook; 14.import org.apache.poi.ss.util.CellRangeAddress; 15. 16.

17./*********************************************************************** 18. *

19. * poiCreate.java

20. * @copyright Copyright: 2009-2012 21. * @creator 周辉

22. * @create-time Mar 9, 2010 2:27:52 PM 23. * @revision $Id: *

24. ***********************************************************************/

25.public class poiCreate { 26.

27. /**

28. * @param args 29. */

30. public static void main(String[] args) throws Exception { 31. //创建一个EXCEL

32. Workbook wb = new HSSFWorkbook();

33. DataFormat format = wb.createDataFormat(); 34. CellStyle style; 35. //创建一个SHEET

36. Sheet sheet1 = wb.createSheet(\产品清单\

37. String[] title = {\编号\产品名称\产品价格\产品数量\生产日期\产地\是否出口\38. int i=0; 39. //创建一行

40. Row row = sheet1.createRow((short)0); 41. //填充标题

42. for (String s:title){

43. Cell cell = row.createCell(i); 44. cell.setCellValue(s); 45. i++; 46. }

47. Row row1 = sheet1.createRow((short)1); 48. //下面是填充数据

49. row1.createCell(0).setCellValue(20071001); 50. row1.createCell(1).setCellValue(\金鸽瓜子\51. //创建一个单元格子

52. Cell cell2=row1.createCell(2); 53. // 填充产品价格

54. cell2.setCellValue(2.45); 55. style = wb.createCellStyle();

56. style.setDataFormat(format.getFormat(\57. //设定样式

58. cell2.setCellStyle(style); 59. // 填充产品数量

60. row1.createCell(3).setCellValue(200); 61. /*

62. * 定义显示日期的公共格式 63. * 如:yyyy-MM-dd hh:mm 64. * */

65. SimpleDateFormat sdf = new SimpleDateFormat(\\

66. String newdate = sdf.format(new Date()); 67. // 填充出产日期

68. row1.createCell(4).setCellValue(newdate); 69. row1.createCell(5).setCellValue(\陕西西安\70. /*

71. * 显示布尔值 72. * */

73. row1.createCell(6).setCellValue(true); 74. /*

75. * 合并单元格 76. * 通过

writablesheet.mergeCells(int x,int y,int m,int n);来实现的 77. * 表示将first row, last row,first column,last column 78. * 79. * */

80. Row row2 = sheet1.createRow((short) 2); 81. Cell cell3 = row2.createCell((short) 0); 82. cell3.setCellValue(\合并了三个单元格\

83. sheet1.addMergedRegion(new CellRangeAddress(2,2,0,2));

84.

85. FileOutputStream fileOut = new FileOutputStream(\st.xls\

86. wb.write(fileOut); 87. fileOut.close(); 88. 89.

90. } 91. 92.}

上面代码2中方式生成 2张报表,涉及到基本生成报表中的几种单元格类型。 POI 用的JAR poi-3.6-20091214.jar jxl 用到的jar jxl-2.6.jar 2 种方式都相对比较好用,个人推荐使用POI (apache的项目) 相关参考资料可以去官方网站查看

http://poi.apache.org/spreadsheet/quick-guide.html

近期看了下POI,写了一些小例子,结合反射技术对EXCEL的导入到出进行了简单封装,主要实现功能如下:

(1)导入EXCEL文档到List>中

(2)导出List>类型数据到EXCEL中 (3)导出List类型的数据到EXCEL中

其中第(3)个方法使用了相应的格式规范加反射,具体使用时只要配置好List中对象的取值方法名,可以实现很大程度上的复用

注:支持对象的深度导出,即List中存放对象的取值方法返回值是另一个对象的引用,最终需要的值在这个引用对象中

多余的话就不说了,上代码(Demo工程放到了文章后面的附件中): POI封装类(主类)MyPOI.java Java代码

1. package com.lightgjc1.poi; 2.

3. import java.io.File;

4. import java.io.FileInputStream; 5. import java.io.FileOutputStream; 6. import java.io.IOException;

7. import java.lang.reflect.Method; 8. import java.util.ArrayList; 9. import java.util.HashMap; 10.import java.util.List; 11.import java.util.Map; 12.

13.import org.apache.poi.hssf.usermodel.HSSFCell; 14.import org.apache.poi.hssf.usermodel.HSSFRow; 15.import org.apache.poi.hssf.usermodel.HSSFSheet; 16.import org.apache.poi.hssf.usermodel.HSSFWorkbook; 17.

18.public class MyPOI { 19. 20. /**

21. * 导入Excel文件

22. * 内容以List>的方式存放 23. * @param excelFile : Excel文件对象

24. * @param strKeys : Map的Key列表,Value为相应的sheet一行中各列的值 25. * @return 26. */

27. public static List> importExcelToMap(File excelFile, String strKeys) {

28. String[] strKey = strKeys.split(\

29. List> listMap = new ArrayList>(); 30.

31. int i = 1; 32. try {

33. HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(excelFile));

34. HSSFSheet sheet = workbook.getSheetAt(0); 35. while (true) {

36. HSSFRow row = sheet.getRow(i); 37. if (row == null) 38. break; 39.

40. Map map = new HashMap();

41. for(int keyIndex = 0; keyIndex < strKey.length; keyIndex++){

42. map.put(strKey[keyIndex], row.getCell(keyIndex).getStringCellValue()); 43. }

44. listMap.add(map); 45. 46. i++; 47. }

48. } catch (Exception e) { 49. e.printStackTrace(); 50.

51. System.out.println(\导入中断,错误位置:第\行数据!\52. } 53.

54. return listMap; 55. } 56. 57. /**

58. * 导出Excel文件

59. * 数据源的数据格式为List> 60. * @param objList : Excel数据源

61. * @param title : 新建Sheet的名称 62. * @param strTitle : Sheet各列的标题(第一行各列的名称) 63. * @param strBody : Sheet各列的取值方法名(各列的值在objClass中get方法名称)

64. * @param outputPath: Excel文档保存路径 65. */

66. public static void exportExcelByMap(List> objList, String title, String strTitle, String strBody, String outputPath) {

67. // 创建工作簿(Excel文件)

68. HSSFWorkbook workbook = new HSSFWorkbook(); 69.

70. // 创建Excel工作簿的第一个Sheet页

71. HSSFSheet sheet = workbook.createSheet(title); 72.

73. // 创建Sheet页的文件头(第一行) 74. createTitle(sheet, strTitle); 75.

76. // 创建Sheet页的文件体(后续行)

77. String[] strArray = strBody.split(\

78. for(int objIndex = 0; objIndex < objList.size(); objIndex++) {

79. Map map = objList.get(objIndex);

80. HSSFRow row = sheet.createRow(objIndex + 1); 81. for(int i = 0; i < strArray.length; i++) { 82. HSSFCell cell = row.createCell(i);

83. cell.setCellType(HSSFCell.CELL_TYPE_STRING); 84. cell.setCellValue(map.get(strArray[i]).toString());

85. } 86. } 87.

88. // 保存Excel文件

89. saveExcelFile(workbook, outputPath); 90. } 91. 92. /**

93. * 导出Excle文档 94. *

95. * @param objList : Excel数据源

96. * @param objClass : Excel数据源中的数据类型 97. * @param title : 新建Sheet的名称 98. * ex: title = \员工表\99. * @param strTitle : Sheet各列的标题(第一行各列的名称) 100. * ex: strTitle = \员工代码,员工姓名,性别,出生日期,籍贯,所属机构,联系电话,电子邮件,助记码\101. * @param strBody : Sheet各列的取值方法名(各列的值在objClass中get方法名称)

102. * ex: strBody = \getBirthday,getHomeplace.getName,getOrg.getShortName,getContactTel,getEmail,getZjm\

103. * @param outputPath: Excel文档保存路径 104. */

105. public static void exportExcelByObject(List objList, Class objClass, String title, String strTitle, String strBody, String outputPath) {

106. // 初始化工作簿

107. HSSFWorkbook workbook = initWorkbook(objList, objClass, title, strTitle, strBody); 108. // 保存Excel文件

109. saveExcelFile(workbook, outputPath); 110. } 111. /**

112. * 初始化工作簿 113. *

114. * @param objList : Excel数据源

115. * @param objClass : Excel数据源中的数据类型 116. * @param title : 新建Sheet的名称 117. * @param strTitle : Sheet各列的标题(第一行各列的名称)

118. * @param strBody : Sheet各列的取值方法名(各列的值在objClass中get方法名称) 119. */

120. private static HSSFWorkbook initWorkbook(List objList, Class objClass, String title, String strTitle, String strBody){

121. // 创建工作簿(Excel文件)

122. HSSFWorkbook workbook = new HSSFWorkbook(); 123.

124. // 创建Excel工作簿的第一个Sheet页

125. HSSFSheet sheet = workbook.createSheet(title); 126.

127. // 创建Sheet页的文件头(第一行) 128. createTitle(sheet, strTitle); 129.

130. // 创建Sheet页的文件体(后续行)

131. createBody(objList, objClass, sheet, strBody); 132.

133. return workbook; 134. } 135. 136. /**

137. * 创建Excel当前sheet页的头信息 138. *

139. * @param sheet : Excel工作簿的一个sheet

140. * @param strTitle : sheet头信息列表(sheet第一行各列值)

141. */

142. private static void createTitle(HSSFSheet sheet, String strTitle){

143. HSSFRow row = sheet.createRow(0); // 创建该页的一行

144. HSSFCell cell = null; 145.

146. String[] strArray = strTitle.split(\147.

148. for(int i = 0; i < strArray.length; i++) {

149. cell = row.createCell(i); // 创建该行的一列 150. cell.setCellType(HSSFCell.CELL_TYPE_STRING); 151. cell.setCellValue(strArray[i]); 152. } 153. 154. } 155. 156. /**

157. * 创建Excel当前sheet页的体信息 158. *

159. * @param objList : Excel数据源

160. * @param objClass : Excel数据源中的数据类型 161. * @param sheet : Excel工作簿的sheet页 162. * @param strBody : Sheet各列的取值方法名(各列的值在objClass中get方法名称) 163. */

164. private static void createBody(List objList, Class objClass, HSSFSheet sheet, String strBody){

165. String[] targetMethod = strBody.split(\166. Method[] ms = objClass.getMethods(); 167.

168. // 循环objList对象列表(生成sheet的行)

169. for(int objIndex = 0; objIndex < objList.size(); objIndex++){

170. Object obj = objList.get(objIndex);

171. HSSFRow row = sheet.createRow(objIndex + 1); 172. // 循环strBody目标方法数组(生成sheet的列) 173. for(int strIndex = 0; strIndex < targetMethod.length; strIndex++) {

174. String targetMethodName = targetMethod[strIndex];

175. // 循环ms方法数组,找到目标方法(strBody中指定的方法)并调用

176. for(int i = 0; i < ms.length; i++) { 177. Method srcMethod = ms[i];

178. int len = targetMethodName.indexOf(\) < 0 ? targetMethodName.length() : targetMethodName.indexOf(\\

179. if (srcMethod.getName().equals(targetMethodName.substring(0, len))) {

180. HSSFCell cell = row.createCell(strIndex);

181. cell.setCellType(HSSFCell.CELL_TYPE_STRING);

182. try {

183. // 如果方法返回一个引用类型的值

184. if (targetMethodName.contains(\

185. cell.setCellValue(referenceInvoke(targetMethodName, obj));

186. // 如果方法返回一个普通属性 187. } else {

188. cell.setCellValue((srcMethod.invoke(obj)).toString());

189. }

190. } catch (Exception e) { 191. e.printStackTrace(); 192. } 193. } 194. } 195. } 196. } 197. 198. } 199. 200. /**

201. * 方法返回的是一个对象的引用(如:getHomeplace.getName类型的方法序列)

202. * 按方法序列逐层调用直到最后放回基本类型的值 203. *

204. * @param targetMethod : obj对象所包含的方法列 205. * @param obj : 待处理的对象

206. * @return

207. */ //getHomeplace.getName emp(obj)

208. private static String referenceInvoke(String targetMethod, Object obj) {

209. // 截取方法序列的第一个方法(即截取属于obj对象的方法:getHomeplace())

210. String refMethod = targetMethod.substring(0, targetMethod.indexOf(\

211. // 获得后续方法序列(getName())

212. targetMethod = targetMethod.substring(targetMethod.indexOf(\213. try {

214. // 获得第一个方法的执行结果(即obj方法执行的结果:obj.getHomeplace())

215. obj = obj.getClass().getMethod(refMethod).invoke(obj);

216. } catch (Exception e) { 217. e.printStackTrace(); 218. } 219.

220. // 如果方法序列没到最后一节

221. if (targetMethod.contains(\

222. return referenceInvoke(targetMethod, obj); 223. // 如果方法序列到达最后一节 224. } else { 225. try {

226. // 通过obj对象获得该方法链的最后一个方法并调用

227. Method tarMethod = obj.getClass().getMethod(targetMethod);

228. return tarMethod.invoke(obj).toString(); 229. } catch (Exception e) { 230. e.printStackTrace();

231. throw new RuntimeException(e); 232. } 233. } 234. 235. } 236. 237. /**

238. * 保存Excel文件 239. *

240. * @param workbook : Excel工作簿

241. * @param outputPath: Excel文件保存路径 242. */

243. private static void saveExcelFile(HSSFWorkbook workbook, String outputPath) { 244. try {

245. FileOutputStream fos = new FileOutputStream(outputPath);

246. workbook.write(fos); 247.

248. fos.flush(); 249. fos.close();

250. } catch (IOException e) { 251. e.printStackTrace(); 252. } 253. } 254. }

测试类POITest.java Java代码

1. package com.lightgjc1.test; 2.

3. import java.io.File;

4. import java.util.ArrayList; 5. import java.util.Date; 6. import java.util.List; 7. import java.util.Map; 8.

9. import junit.framework.TestCase; 10.

11.import com.lightgjc1.domain.Area; 12.import com.lightgjc1.domain.Employee; 13.import com.lightgjc1.domain.OrgType;

14.import com.lightgjc1.domain.Organization; 15.import com.lightgjc1.poi.MyPOI; 16.

17.public class POITest extends TestCase {

18. public void testImportAndExportExcel(){

19. String strKeys = \tHomeplace,setOrg,setContactTel\

20. List> listMap = MyPOI.importExcelToMap(new File(\

21.

22. String[] keys = strKeys.split(\23. for(Map map : listMap) {

24. for(int i = 0; i < keys.length; i++) {

25. System.out.print(map.get(keys[i]) +\26. }

27. System.out.println();

28. System.out.println(\29. } 30.

31. String title = \员工表\

32. String strTitle = \员工代码,员工姓名,性别,出生日期,籍贯,所属机构,机构类型\

33. String strBody = \tHomeplace,setOrg,setContactTel\

34. String outputPath = \

35. MyPOI.exportExcelByMap(listMap, title, strTitle, strBody, outputPath); 36. } 37.

38. public void testExportExcel(){ 39. List objList = initData();

40. Class objClass = Employee.class; 41. String title = \员工表\

42. String strTitle = \员工代码,员工姓名,性别,出生日期,籍贯,所属机构,机构类型\

43. String strBody = \tHomeplace.getName,getOrg.getShortName,getOrg.getOrgType.getName\

44. String outputPath = \45.

46. MyPOI.exportExcelByObject(objList, objClass, title, strTitle, strBody, outputPath); 47. } 48.

49. private List initData(){

50. List empList = new ArrayList(); 51.

52. Employee emp = null;

53. for(int i = 0; i < 10; i++) { 54. emp = new Employee(); 55. emp.setCode(i +\号\56. emp.setName(i +\号\

57. emp.setSex(i % 2 == 0 ? \女\男\

58. emp.setBirthday(new Date()); 59. 60.

61. Area area = new Area(); 62. area.setName(i +\市\63. emp.setHomeplace(area); 64. 65.

66. OrgType orgType = new OrgType(); 67. orgType.setName(\机构类型\68.

69. Organization org = new Organization(); 70. org.setOrgType(orgType);

71. org.setShortName(\机构\72.

73. emp.setOrg(org); 74. 75.

76. empList.add(emp); 77. } 78.

79. return empList; 80. } 81.}

其他工具类(存放数据的实体类) Employee.java 用来存放员工数据 Java代码

1. package com.lightgjc1.domain; 2.

3. import java.util.Date; 4.

5. public class Employee { 6.

7. private String id; 8.

9. private String code; 10.

11. private String name; 12.

13. private String sex; 14.

15. private Date birthday; 16.

17. private String email; 18.

19. private String contactTel; 20.

21. private String zjm; 22.

23. private Organization org = new Organization(); 24.

25. private Area homeplace; 26.

27. public String getId() { 28. return id; 29. } 30.

31. public void setId(String id) { 32. this.id = id; 33. } 34.

35. public String getCode() { 36. return code; 37. } 38.

39. public void setCode(String code) { 40. this.code = code; 41. } 42.

43. public String getName() { 44. return name; 45. } 46.

47. public void setName(String name) { 48. this.name = name; 49. } 50.

51. public String getSex() { 52. return sex; 53. } 54.

55. public void setSex(String sex) { 56. this.sex = sex;

57. } 58.

59. public Date getBirthday() { 60. return birthday; 61. } 62.

63. public void setBirthday(Date birthday) { 64. this.birthday = birthday; 65. } 66.

67. public String getEmail() { 68. return email; 69. } 70.

71. public void setEmail(String email) { 72. this.email = email; 73. } 74.

75. public String getContactTel() { 76. return contactTel; 77. } 78.

79. public void setContactTel(String contactTel) { 80. this.contactTel = contactTel; 81. } 82.

83. public String getZjm() { 84. return zjm; 85. } 86.

87. public void setZjm(String zjm) { 88. this.zjm = zjm; 89. } 90.

91. public Organization getOrg() { 92. return org; 93. } 94.

95. public void setOrg(Organization org) { 96. this.org = org; 97. } 98.

99. public Area getHomeplace() { 100. return homeplace;

101. 102. 103. 104. 105. 106. 107. 108. }

public void setHomeplace(Area homeplace) { this.homeplace = homeplace; } }

Organization.java

用来存放员工所属的组织部门 Java代码

1. package com.lightgjc1.domain; 2.

3. import java.util.Set; 4.

5. public class Organization { 6.

7. private String id; 8.

9. private String code; 10.

11. private String fullName; 12.

13. private String shortName; 14.

15. private String manager; 16.

17. private String desc; 18.

19. //*-----1

20. private OrgType orgType; 21.

22. //*-----1

23. private Organization parent; 24.

25. //1-----*

26. private Set children; 27.

28. public String getId() { 29. return id;

30. } 31.

32. public void setId(String id) { 33. this.id = id; 34. } 35.

36. public String getCode() { 37. return code; 38. } 39.

40. public void setCode(String code) { 41. this.code = code; 42. } 43.

44. public String getFullName() { 45. return fullName; 46. } 47.

48. public void setFullName(String fullName) { 49. this.fullName = fullName; 50. } 51.

52. public String getShortName() { 53. return shortName; 54. } 55.

56. public void setShortName(String shortName) { 57. this.shortName = shortName; 58. } 59.

60. public String getManager() { 61. return manager; 62. } 63.

64. public void setManager(String manager) { 65. this.manager = manager; 66. } 67.

68. public String getDesc() { 69. return desc; 70. } 71.

72. public void setDesc(String desc) { 73. this.desc = desc;

74. } 75.

76. public OrgType getOrgType() { 77. return orgType; 78. } 79.

80. public void setOrgType(OrgType orgType) { 81. this.orgType = orgType; 82. } 83.

84. public Organization getParent() { 85. return parent; 86. } 87.

88. public void setParent(Organization parent) { 89. this.parent = parent; 90. } 91.

92. public Set getChildren() { 93. return children; 94. } 95.

96. public void setChildren(Set children) { 97. this.children = children; 98. } 99. 100. }

OrgType.java

用来存放员工所属组织部门的部门类型 Java代码

1. package com.lightgjc1.domain; 2.

3. public class OrgType { 4.

5. private String id; 6.

7. //如果使用数值类型作为主键,建议使用包装类 8. //private Integer id; 9. //private int id; 10.

11. private String code; 12.

13. private String name; 14.

15. public String getId() { 16. return id; 17. } 18.

19. public void setId(String id) { 20. this.id = id; 21. } 22.

23. public String getCode() { 24. return code; 25. } 26.

27. public void setCode(String code) { 28. this.code = code; 29. } 30.

31. public String getName() { 32. return name; 33. } 34.

35. public void setName(String name) { 36. this.name = name; 37. } 38. 39.}

Area.java

用来存放员工的籍贯信息 Java代码

1. package com.lightgjc1.domain; 2.

3. import java.util.Set; 4.

5. public class Area { 6.

7. private String id; 8.

9. private String code; 10.

11. private String name; 12.

13. private Area parent; 14.

15. private Set children; 16.

17. public String getId() { 18. return id; 19. } 20.

21. public void setId(String id) { 22. this.id = id; 23. } 24.

25. public String getCode() { 26. return code; 27. } 28.

29. public void setCode(String code) { 30. this.code = code; 31. } 32.

33. public String getName() { 34. return name; 35. } 36.

37. public void setName(String name) { 38. this.name = name; 39. } 40.

41. public Area getParent() { 42. return parent; 43. } 44.

45. public void setParent(Area parent) { 46. this.parent = parent; 47. } 48.

49. public Set getChildren() { 50. return children; 51. } 52.

53. public void setChildren(Set children) { 54. this.children = children; 55. } 56. 57.}

jxl的一些总结

要往xls文件里面写入数据的时候需要注意的是第一要新建一个xls文件 OutputStream os=new FileOutputStream(\

再建完这个文件的时候再建立工作文件

jxl.write.WritableWorkbook wwb = Workbook.createWorkbook(new File(os));

如果这个文件已经存在,那么我们可以在这个文件里面加入一个sheet为了和以前的数据进行分开;

jxl.write.WritableSheet ws = wwb.createSheet(\在createSheet方法里前面的参数是sheet名,后面是要操作的sheet号

接下来就可以往这个文件里面写入数据了

写入数据的时候注意的格式

(1)添加的字体样式

jxl.write.WritableFont wf = new jxl.write.WritableFont(WritableFont.TIMES, 18, WritableFont.BOLD, true); WritableFont()方法里参数说明:

这个方法算是一个容器,可以放进去好多属性 第一个: TIMES是字体大小,他写的是18

第二个: BOLD是判断是否为斜体,选择true时为斜体 第三个: ARIAL

第四个: UnderlineStyle.NO_UNDERLINE 下划线 第五个: jxl.format.Colour.RED 字体颜色是红色的

jxl.write.WritableCellFormat wcfF = new jxl.write.WritableCellFormat(wf);

jxl.write.Label labelC = new jxl.write.Label(0, 0, \,wcfF); ws.addCell(labelC);

在Label()方法里面有三个参数 第一个是代表列数, 第二是代表行数, 第三个代表要写入的内容

第四个是可选项,是输入这个label里面的样式

然后通过写sheet的方法addCell()把内容写进sheet里面。

(2)添加带有formatting的Number对象

jxl.write.NumberFormat nf = new jxl.write.NumberFormat(\

(3)添加Number对象

(3.1)显示number对象数据的格式

jxl.write.NumberFormat nf = new jxl.write.NumberFormat(\jxl.write.WritableCellFormat wcfN = new jxl.write.WritableCellFormat(nf);

jxl.write.Number labelNF = new jxl.write.Number(1, 1, 3.1415926, wcfN); ws.addCell(labelNF); Number()方法参数说明: 前两上表示输入的位置 第三个表示输入的内容

(4)添加Boolean对象

jxl.write.Boolean labelB = new jxl.write.Boolean(0, 2, false); ws.addCell(labelB);

(5)添加DateTime对象

jxl.write.DateTime labelDT = new jxl.write.DateTime(0, 3, new java.util.Date()); ws.addCell(labelDT); DateTime()方法的参数说明 前两个表示输入的位置 第三个表示输入的当前时间

(6)添加带有formatting的DateFormat对象 这个显示当前时间的所有信息,包括年月日小时分秒

jxl.write.DateFormat df = new jxl.write.DateFormat(\jxl.write.WritableCellFormat wcfDF = new jxl.write.WritableCellFormat(df);

jxl.write.DateTime labelDTF = new jxl.write.DateTime(1, 3, new java.util.Date(), wcfDF); ws.addCell(labelDTF);

(7)添加带有字体颜色Formatting的对象

jxl.write.WritableFont wfc = new jxl.write.WritableFont(WritableFont.ARIAL, 10, WritableFont.NO_BOLD, false,UnderlineStyle.NO_UNDERLINE, jxl.format.Colour.RED); jxl.write.WritableCellFormat wcfFC = new jxl.write.WritableCellFormat(wfc);

import=\

jxl.write.WritableFont wfc = new

jxl.write.WritableFont(WritableFont.ARIAL,20,WritableFont.BOLD,false,UnderlineStyle.NO_UNDERLINE,jxl.format.Colour.GREEN);

(8)设置单元格样式

jxl.write.WritableCellFormat wcfFC = new jxl.write.WritableCellFormat(wfc); wcfFC.setBackGround(jxl.format.Colour.RED);//设置单元格的颜色为红色 wcfFC = new jxl.write.Label(6,0,\

可以读,但是不能生成公式,任何类型公式最后的计算值都可以读出; 应用示例

从Excel文件读取数据表

Java Excel API既可以从本地文件系统的一个文件(.xls),也可以从输入流中读取Excel数据表。读取Excel数据

表的第一步是创建Workbook(术语:工作薄),下面的代码片段举例说明了应该如何操作:(完整代码见

ExcelReading.java)

import java.io.*; import jxl.*; … … … … try {

//构建Workbook对象, 只读Workbook对象 //直接从本地文件创建Workbook //从输入流创建Workbook

InputStream is = new FileInputStream(sourcefile); jxl.Workbook rwb = Workbook.getWorkbook(is); }

catch (Exception e) {

e.printStackTrace(); }

一旦创建了Workbook,我们就可以通过它来访问Excel Sheet(术语:工作表)。参考下面的代码片段:

//获取第一张Sheet表 Sheet rs = rwb.getSheet(0);

我们既可能通过Sheet的名称来访问它,也可以通过下标来访问它。如果通过下标来访问的话,要注意的一点

是下标从0开始,就像数组一样。

一旦得到了Sheet,我们就可以通过它来访问Excel Cell(术语:单元格)。参考下面的代码片段:

//获取第一行,第一列的值 Cell c00 = rs.getCell(0, 0); String strc00 = c00.getContents(); //获取第一行,第二列的值 Cell c10 = rs.getCell(1, 0); String strc10 = c10.getContents(); //获取第二行,第二列的值 Cell c11 = rs.getCell(1, 1); String strc11 = c11.getContents();

System.out.println(\c00.getType());

System.out.println(\c10.getType());

System.out.println(\c11.getType());

如果仅仅是取得Cell的值,我们可以方便地通过getContents()方法,它可以将任何类型的Cell值都作为一个

字符串返回。示例代码中Cell(0, 0)是文本型,Cell(1, 0)是数字型,Cell(1,1)是日期型,通过getContents()

,三种类型的返回值都是字符型。

如果有需要知道Cell内容的确切类型,API也提供了一系列的方法。参考下面的代码片段: String strc00 = null; double strc10 = 0.00; Date strc11 = null; Cell c00 = rs.getCell(0, 0); Cell c10 = rs.getCell(1, 0); Cell c11 = rs.getCell(1, 1);

if(c00.getType() == CellType.LABEL) {

LabelCell labelc00 = (LabelCell)c00; strc00 = labelc00.getString(); }

if(c10.getType() == CellType.NUMBER) {

NmberCell numc10 = (NumberCell)c10; strc10 = numc10.getValue(); }

if(c11.getType() == CellType.DATE)

本文来源:https://www.bwwdw.com/article/bo53.html

Top