一.POI简介
Jakarta POI 是apache的子项目,目标是处理ole2对象。它提供了一组操纵Windows文档的Java API 。目前比较成熟的是HSSF接口,处理MS Excel(97-2002)对象。它不象我们仅仅是用csv生成的没有格式的可以由Excel转换的东西,而是真正的Excel对象,你可以控制一些属性如sheet,cell等等。
二.HSSF概况
HSSF 是Horrible SpreadSheet Format的缩写,也即“讨厌的电子表格格式”。 也许HSSF的名字有点滑稽,就本质而言它是一个非常严肃、正规的API。通过HSSF,你可以用纯Java代码来读取、写入、修改Excel文件。
HSSF 为读取操作提供了两类API:usermodel和eventusermodel,即“用户模型”和“事件-用户模型”。前者很好理解,后者比较抽象,但操作效率要高得多。
三.开始编码
1 . 准备工作
要求:JDK 1.4+POI开发包
可以到 http://www.apache.org/dyn/closer.cgi/jakarta/poi/ 最新的POI工具包
2 . EXCEL 结构
HSSFWorkbook excell 文档对象介绍
HSSFSheet excell的表单
HSSFRow excell的行
HSSFCell excell的格子单元
HSSFFont excell字体
HSSFName 名称
HSSFDataFormat 日期格式
HSSFHeader sheet头
HSSFFooter sheet尾
和这个样式
HSSFCellStyle cell样式
辅助操作包括
HSSFDateUtil 日期
HSSFPrintSetup 打印
HSSFErrorConstants 错误信息表
4 . 可参考文档
POI 主页:http://jakarta.apache.org/poi/,
初学者如何快速上手使用POI HSSF
http://jakarta.apache.org/poi/hssf/quick-guide.html 。
代码例子 http://blog.java-cn.com/user1/6749/archives/2005/18347.html
里面有很多例子代码,可以很方便上手。
四.使用心得
POI HSSF 的usermodel包把Excel文件映射成我们熟悉的结构,诸如Workbook、Sheet、Row、Cell等,它把整个结构以一组对象的形式保存在内存之中,便于理解,操作方便,基本上能够满足我们的要求,所以说这个一个不错的选择。
Tips: 设置打开文件显示的那个sheet 方法:wb.setActiveSheet(3);
复制sheet: wb.cloneSheet(0);
1.创建工作簿 (WORKBOOK)
1. HSSFWorkbook wb = new HSSFWorkbook();
2. FileOutputStream fileOut = new FileOutputStream("workbook.xls");
3. wb.write(fileOut);
4. fileOut.close();
2.创建工作表(SHEET)
1. HSSFWorkbook wb = new HSSFWorkbook();
2. HSSFSheet sheet1 = wb.createSheet("new sheet");
3. HSSFSheet sheet2 = wb.createSheet("second sheet");
4. FileOutputStream fileOut = new FileOutputStream("workbook.xls");
5. wb.write(fileOut);
6. fileOut.close();
3.创建单元格(CELL)
1. HSSFWorkbook wb = new HSSFWorkbook();
2. HSSFSheet sheet = wb.createSheet("new sheet");
3. // Create a row and put some cells in it. Rows are 0 based.
4. HSSFRow row = sheet.createRow((short)0);
5. // Create a cell and put a value in it.
6. HSSFCell cell = row.createCell((short)0);
7. cell.setCellValue(1);
8. // Or do it on one line.
9. row.createCell((short)1).setCellValue(1.2);
10. row.createCell((short)2).setCellValue("This is a string");
11. row.createCell((short)3).setCellValue(true);
12. // Write the output to a file
13. FileOutputStream fileOut = new FileOutputStream("workbook.xls");
14. wb.write(fileOut);
15. fileOut.close();
4.创建指定单元格式的单元格
1. HSSFWorkbook wb = new HSSFWorkbook();
2. HSSFSheet sheet = wb.createSheet("new sheet");
3. // Create a row and put some cells in it. Rows are 0 based.
4. HSSFRow row = sheet.createRow((short)0);
5. // Create a cell and put a date value in it. The first cell is not styled
6. // as a date.
7. HSSFCell cell = row.createCell((short)0);
8. cell.setCellValue(new Date());
9. // we style the second cell as a date (and time). It is important to
10. // create a new cell style from the workbook otherwise you can end up
11. // modifying the built in style and effecting not only this cell but other cells.
12. HSSFCellStyle cellStyle = wb.createCellStyle();
13. cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm"));
14. cell = row.createCell((short)1);
15. cell.setCellValue(new Date());
16. cell.setCellStyle(cellStyle);
17. // Write the output to a file
18. FileOutputStream fileOut = new FileOutputStream("workbook.xls");
19. wb.write(fileOut);
20. fileOut.close();
5. 单元格的不同格式
1. HSSFWorkbook wb = new HSSFWorkbook();
2. HSSFSheet sheet = wb.createSheet("new sheet");
3. HSSFRow row = sheet.createRow((short)2);
4. row.createCell((short) 0).setCellValue(1.1);
5. row.createCell((short) 1).setCellValue(new Date());
6. row.createCell((short) 2).setCellValue("a string");
7. row.createCell((short) 3).setCellValue(true);
8. row.createCell((short) 4).setCellType(HSSFCell.CELL_TYPE_ERROR);
9. // Write the output to a file
10. FileOutputStream fileOut = new FileOutputStream("workbook.xls");
11. wb.write(fileOut);
12. fileOut.close();
6.单元格的不通对齐方式
1. public static void main(String[] args)
2. throws IOException
3. {
4. HSSFWorkbook wb = new HSSFWorkbook();
5. HSSFSheet sheet = wb.createSheet("new sheet");
6. HSSFRow row = sheet.createRow((short) 2);
7. createCell(wb, row, (short) 0, HSSFCellStyle.ALIGN_CENTER);
8. createCell(wb, row, (short) 1, HSSFCellStyle.ALIGN_CENTER_SELECTION);
9. createCell(wb, row, (short) 2, HSSFCellStyle.ALIGN_FILL);
10. createCell(wb, row, (short) 3, HSSFCellStyle.ALIGN_GENERAL);
11. createCell(wb, row, (short) 4, HSSFCellStyle.ALIGN_JUSTIFY);
12. createCell(wb, row, (short) 5, HSSFCellStyle.ALIGN_LEFT);
13. createCell(wb, row, (short) 6, HSSFCellStyle.ALIGN_RIGHT);
14. // Write the output to a file
15. FileOutputStream fileOut = new FileOutputStream("workbook.xls");
16. wb.write(fileOut);
17. fileOut.close();
18. }
19. /**
20. * Creates a cell and aligns it a certain way.
21. *
22. * @param wb the workbook
23. * @param row the row to create the cell in
24. * @param column the column number to create the cell in
25. * @param align the alignment for the cell.
26. */
27. private static void createCell(HSSFWorkbook wb, HSSFRow row, short column, short align)
28. {
29. HSSFCell cell = row.createCell(column);
30. cell.setCellValue("Align It");
31. HSSFCellStyle cellStyle = wb.createCellStyle();
32. cellStyle.setAlignment(align);
33. cell.setCellStyle(cellStyle);
34. }
7.单元格的边框设置
1. //Working with borders
2. HSSFWorkbook wb = new HSSFWorkbook();
3. HSSFSheet sheet = wb.createSheet("new sheet");
4. // Create a row and put some cells in it. Rows are 0 based.
5. HSSFRow row = sheet.createRow((short) 1);
6. // Create a cell and put a value in it.
7. HSSFCell cell = row.createCell((short) 1);
8. cell.setCellValue(4);
9. // Style the cell with borders all around.
10. HSSFCellStyle style = wb.createCellStyle();
11. style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
12. style.setBottomBorderColor(HSSFColor.BLACK.index);
13. style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
14. style.setLeftBorderColor(HSSFColor.GREEN.index);
15. style.setBorderRight(HSSFCellStyle.BORDER_THIN);
16. style.setRightBorderColor(HSSFColor.BLUE.index);
17. style.setBorderTop(HSSFCellStyle.BORDER_MEDIUM_DASHED);
18. style.setTopBorderColor(HSSFColor.BLACK.index);
19. cell.setCellStyle(style);
20. // Write the output to a file
21. FileOutputStream fileOut = new FileOutputStream("workbook.xls");
22. wb.write(fileOut);
23. fileOut.close();
8.填充和颜色设置
1. HSSFWorkbook wb = new HSSFWorkbook();
2. HSSFSheet sheet = wb.createSheet("new sheet");
3. // Create a row and put some cells in it. Rows are 0 based.
4. HSSFRow row = sheet.createRow((short) 1);
5. // Aqua background
6. HSSFCellStyle style = wb.createCellStyle();
7. style.setFillBackgroundColor(HSSFColor.AQUA.index);
8. style.setFillPattern(HSSFCellStyle.BIG_SPOTS);
9. HSSFCell cell = row.createCell((short) 1);
10. cell.setCellValue("X");
11. cell.setCellStyle(style);
12. // Orange "foreground", foreground being the fill foreground not the font color.
13. style = wb.createCellStyle();
14. style.setFillForegroundColor(HSSFColor.ORANGE.index);
15. style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
16. cell = row.createCell((short) 2);
17. cell.setCellValue("X");
18. cell.setCellStyle(style);
19. // Write the output to a file
20. FileOutputStream fileOut = new FileOutputStream("workbook.xls");
21. wb.write(fileOut);
22. fileOut.close();
9.合并单元格操作
1. HSSFWorkbook wb = new HSSFWorkbook();
2. HSSFSheet sheet = wb.createSheet("new sheet");
3. HSSFRow row = sheet.createRow((short) 1);
4. HSSFCell cell = row.createCell((short) 1);
5. cell.setCellValue("This is a test of merging");
6. sheet.addMergedRegion(new Region(1,(short)1,1,(short)2));
7. // Write the output to a file
8. FileOutputStream fileOut = new FileOutputStream("workbook.xls");
9. wb.write(fileOut);
10. fileOut.close();
9.1合并单元格边框的解决办法
1. private void setRegionStyle(HSSFSheet sheet, Region region , HSSFCellStyle cs) {
2. int toprowNum = region.getRowFrom();
3. for (int i = region.getRowFrom(); i <= region.getRowTo(); i ++) {
4. HSSFRow row = HSSFCellUtil.getRow(i, sheet);
5. for (int j = region.getColumnFrom(); j <= region.getColumnTo(); j++) {
6. HSSFCell cell = HSSFCellUtil.getCell(row, (short)j);
7. cell.setCellStyle(cs);
8. }
9. }
10. }
10.字体设置
1. HSSFWorkbook wb = new HSSFWorkbook();
2. HSSFSheet sheet = wb.createSheet("new sheet");
3. // Create a row and put some cells in it. Rows are 0 based.
4. HSSFRow row = sheet.createRow((short) 1);
5. // Create a new font and alter it.
6. HSSFFont font = wb.createFont();
7. font.setFontHeightInPoints((short)24);
8. font.setFontName("Courier New");
9. font.setItalic(true);
10. font.setStrikeout(true);
11. // Fonts are set into a style so create a new one to use.
12. HSSFCellStyle style = wb.createCellStyle();
13. style.setFont(font);
14. // Create a cell and put a value in it.
15. HSSFCell cell = row.createCell((short) 1);
16. cell.setCellValue("This is a test of fonts");
17. cell.setCellStyle(style);
18. // Write the output to a file
19. FileOutputStream fileOut = new FileOutputStream("workbook.xls");
20. wb.write(fileOut);
21. fileOut.close();
11.自定义颜色
1. HSSFWorkbook wb = new HSSFWorkbook();
2. HSSFSheet sheet = wb.createSheet();
3. HSSFRow row = sheet.createRow((short) 0);
4. HSSFCell cell = row.createCell((short) 0);
5. cell.setCellValue("Default Palette");
6. //apply some colors from the standard palette,
7. // as in the previous examples.
8. //we'll use red text on a lime background
9. HSSFCellStyle style = wb.createCellStyle();
10. style.setFillForegroundColor(HSSFColor.LIME.index);
11. style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
12. HSSFFont font = wb.createFont();
13. font.setColor(HSSFColor.RED.index);
14. style.setFont(font);
15. cell.setCellStyle(style);
16. //save with the default palette
17. FileOutputStream out = new FileOutputStream("default_palette.xls");
18. wb.write(out);
19. out.close();
20. //now, let's replace RED and LIME in the palette
21. // with a more attractive combination
22. // (lovingly borrowed from freebsd.org)
23. cell.setCellValue("Modified Palette");
24. //creating a custom palette for the workbook
25. HSSFPalette palette = wb.getCustomPalette();
26. //replacing the standard red with freebsd.org red
27. palette.setColorAtIndex(HSSFColor.RED.index,
28. (byte) 153, //RGB red (0-255)
29. (byte) 0, //RGB green
30. (byte) 0 //RGB blue
31. );
32. //replacing lime with freebsd.org gold
33. palette.setColorAtIndex(HSSFColor.LIME.index, (byte) 255, (byte) 204, (byte) 102);
34. //save with the modified palette
35. // note that wherever we have previously used RED or LIME, the
36. // new colors magically appear
37. out = new FileOutputStream("modified_palette.xls");
38. wb.write(out);
39. out.close();
12.读和重写EXCEL文件
1. POIFSFileSystem fs =
2. new POIFSFileSystem(new FileInputStream("workbook.xls"));
3. HSSFWorkbook wb = new HSSFWorkbook(fs);
4. HSSFSheet sheet = wb.getSheetAt(0);
5. HSSFRow row = sheet.getRow(2);
6. HSSFCell cell = row.getCell((short)3);
7. if (cell == null)
8. cell = row.createCell((short)3);
9. cell.setCellType(HSSFCell.CELL_TYPE_STRING);
10. cell.setCellValue("a test");
11. // Write the output to a file
12. FileOutputStream fileOut = new FileOutputStream("workbook.xls");
13. wb.write(fileOut);
14. fileOut.close();
13.在EXCEL单元格中使用自动换行
1. HSSFWorkbook wb = new HSSFWorkbook();
2. HSSFSheet s = wb.createSheet();
3. HSSFRow r = null;
4. HSSFCell c = null;
5. HSSFCellStyle cs = wb.createCellStyle();
6. HSSFFont f = wb.createFont();
7. HSSFFont f2 = wb.createFont();
8. cs = wb.createCellStyle();
9. cs.setFont( f2 );
10. //Word Wrap MUST be turned on
11. cs.setWrapText( true );
12. r = s.createRow( (short) 2 );
13. r.setHeight( (short) 0x349 );
14. c = r.createCell( (short) 2 );
15. c.setCellType( HSSFCell.CELL_TYPE_STRING );
16. c.setCellValue( "Use \n with word wrap on to create a new line" );
17. c.setCellStyle( cs );
18. s.setColumnWidth( (short) 2, (short) ( ( 50 * 8 ) / ( (double) 1 / 20 ) ) );
19. FileOutputStream fileOut = new FileOutputStream( "workbook.xls" );
20. wb.write( fileOut );
21. fileOut.close();
14.数字格式自定义
1. HSSFWorkbook wb = new HSSFWorkbook();
2. HSSFSheet sheet = wb.createSheet("format sheet");
3. HSSFCellStyle style;
4. HSSFDataFormat format = wb.createDataFormat();
5. HSSFRow row;
6. HSSFCell cell;
7. short rowNum = 0;
8. short colNum = 0;
9. row = sheet.createRow(rowNum++);
10. cell = row.createCell(colNum);
11. cell.setCellValue(11111.25);
12. style = wb.createCellStyle();
13. style.setDataFormat(format.getFormat("0.0"));
14. cell.setCellStyle(style);
15. row = sheet.createRow(rowNum++);
16. cell = row.createCell(colNum);
17. cell.setCellValue(11111.25);
18. style = wb.createCellStyle();
19. style.setDataFormat(format.getFormat("#,##0.0000"));
20. cell.setCellStyle(style);
21. FileOutputStream fileOut = new FileOutputStream("workbook.xls");
22. wb.write(fileOut);
23. fileOut.close();
15.调整工作单位置
1. HSSFWorkbook wb = new HSSFWorkbook();
2. HSSFSheet sheet = wb.createSheet("format sheet");
3. HSSFPrintSetup ps = sheet.getPrintSetup();
4. sheet.setAutobreaks(true);
5. ps.setFitHeight((short)1);
6. ps.setFitWidth((short)1); // Create various cells and rows for spreadsheet.
7. FileOutputStream fileOut = new FileOutputStream("workbook.xls");
8. wb.write(fileOut);
9. fileOut.close();
16.设置打印区域
1. HSSFWorkbook wb = new HSSFWorkbook();
2. HSSFSheet sheet = wb.createSheet("Sheet1");
3. wb.setPrintArea(0, "$A$1:$C$2");
4. //sets the print area for the first sheet
5. //Alternatively:
6. //wb.setPrintArea(0, 0, 1, 0, 0) is equivalent to using the name reference (See the JavaDocs for more details)
7. // Create various cells and rows for spreadsheet.
8. FileOutputStream fileOut = new FileOutputStream("workbook.xls");
9. wb.write(fileOut);
10. fileOut.close();
17.标注脚注
1. HSSFWorkbook wb = new HSSFWorkbook();
2. HSSFSheet sheet = wb.createSheet("format sheet");
3. HSSFFooter footer = sheet.getFooter()
4. footer.setRight( "Page " + HSSFFooter.page() + " of " + HSSFFooter.numPages() );
5. // Create various cells and rows for spreadsheet.
6. FileOutputStream fileOut = new FileOutputStream("workbook.xls");
7. wb.write(fileOut);
8. fileOut.close();
18.使用方便的内部提供的函数
1. HSSFWorkbook wb = new HSSFWorkbook();
2. HSSFSheet sheet1 = wb.createSheet( "new sheet" );
3. // Create a merged region
4. HSSFRow row = sheet1.createRow( (short) 1 );
5. HSSFRow row2 = sheet1.createRow( (short) 2 );
6. HSSFCell cell = row.createCell( (short) 1 );
7. cell.setCellValue( "This is a test of merging" );
8. Region region = new Region( 1, (short) 1, 4, (short) 4 );
9. sheet1.addMergedRegion( region );
10. // Set the border and border colors.
11. final short borderMediumDashed = HSSFCellStyle.BORDER_MEDIUM_DASHED;
12. HSSFRegionUtil.setBorderBottom( borderMediumDashed,
13. region, sheet1, wb );
14. HSSFRegionUtil.setBorderTop( borderMediumDashed,
15. region, sheet1, wb );
16. HSSFRegionUtil.setBorderLeft( borderMediumDashed,
17. region, sheet1, wb );
18. HSSFRegionUtil.setBorderRight( borderMediumDashed,
19. region, sheet1, wb );
20. HSSFRegionUtil.setBottomBorderColor(HSSFColor.AQUA.index, region, sheet1, wb);
21. HSSFRegionUtil.setTopBorderColor(HSSFColor.AQUA.index, region, sheet1, wb);
22. HSSFRegionUtil.setLeftBorderColor(HSSFColor.AQUA.index, region, sheet1, wb);
23. HSSFRegionUtil.setRightBorderColor(HSSFColor.AQUA.index, region, sheet1, wb);
24. // Shows some usages of HSSFCellUtil
25. HSSFCellStyle style = wb.createCellStyle();
26. style.setIndention((short)4);
27. HSSFCellUtil.createCell(row, 8, "This is the value of the cell", style);
28. HSSFCell cell2 = HSSFCellUtil.createCell( row2, 8, "This is the value of the cell");
29. HSSFCellUtil.setAlignment(cell2, wb, HSSFCellStyle.ALIGN_CENTER);
30. // Write out the workbook
31. FileOutputStream fileOut = new FileOutputStream( "workbook.xls" );
32. wb.write( fileOut );
33. fileOut.close();
19.在工作单中移动行,调整行的上下位置
1. HSSFWorkbook wb = new HSSFWorkbook();
2. HSSFSheet sheet = wb.createSheet("row sheet");
3. // Create various cells and rows for spreadsheet.
4. // Shift rows 6 - 11 on the spreadsheet to the top (rows 0 - 5)
5. sheet.shiftRows(5, 10, -5);
6. FileOutputStream fileOut = new FileOutputStream("workbook.xls");
7. wb.write(fileOut);
8. fileOut.close();
20.选种指定的工作单
1. HSSFWorkbook wb = new HSSFWorkbook();
2. HSSFSheet sheet = wb.createSheet("row sheet");
3. sheet.setSelected(true);
4. // Create various cells and rows for spreadsheet.
5. FileOutputStream fileOut = new FileOutputStream("workbook.xls");
6. wb.write(fileOut);
7. fileOut.close();
21.工作单的放大缩小
1. HSSFWorkbook wb = new HSSFWorkbook();
2. HSSFSheet sheet1 = wb.createSheet("new sheet");
3. sheet1.setZoom(3,4); // 75 percent magnification
4. FileOutputStream fileOut = new FileOutputStream("workbook.xls");
5. wb.write(fileOut);
6. fileOut.close();
22.头注和脚注
1. HSSFWorkbook wb = new HSSFWorkbook();
2. HSSFSheet sheet = wb.createSheet("new sheet");
3. HSSFHeader header = sheet.getHeader();
4. header.setCenter("Center Header");
5. header.setLeft("Left Header");
6. header.setRight(HSSFHeader.font("Stencil-Normal", "Italic") +
7. HSSFHeader.fontSize((short) 16) + "Right w/ Stencil-Normal Italic font and size 16");
8. FileOutputStream fileOut = new FileOutputStream("workbook.xls");
9. wb.write(fileOut);
10. fileOut.close();
23.图片的使用
1. //先把读进来的图片放到一个ByteArrayOutputStream中,以便产生ByteArray
2. ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
3. BufferedImage bufferImg = ImageIO.read(new File("ok.jpg"));
4. ImageIO.write(bufferImg,"jpg",byteArrayOut);
5.
6. //读进一个excel模版
7. FileInputStream fos = new FileInputStream(filePathName+"/stencil.xlt");
8. fs = new POIFSFileSystem(fos);
9. //创建一个工作薄
10. HSSFWorkbook wb = new HSSFWorkbook(fs);
11. HSSFSheet sheet = wb.getSheetAt(0);
12. HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
13. HSSFClientAnchor anchor = new HSSFClientAnchor(0,0,1023,255,(short) 0,0,(short)10,10);
14. patriarch.createPicture(anchor , wb.addPicture(byteArrayOut.toByteArray(),HSSFWorkbook.PICTURE_TYPE_JPEG));
//-------------------------------以上实例代码均来自官方网站
//-------------------------------POI中使用的颜色是用颜色索引来实现,如下:
/*
* 颜色对照表 数字代表颜色索引
8: BLACK
60: BROWN
59: OLIVE_GREEN
58: DARK_GREEN
56: DARK_TEAL
18: DARK_BLUE
32: DARK_BLUE
62: INDIGO
63: GREY_80_PERCENT
53: ORANGE
19: DARK_YELLOW
17: GREEN
21: TEAL
38: TEAL
12: BLUE
39: BLUE
54: BLUE_GREY
23: GREY_50_PERCENT
10: RED
52: LIGHT_ORANGE
50: LIME
57: SEA_GREEN
49: AQUA
48: LIGHT_BLUE
20: VIOLET
36: VIOLET
55: GREY_40_PERCENT
14: PINK
33: PINK
51: GOLD
13: YELLOW
34: YELLOW
11: BRIGHT_GREEN
35: BRIGHT_GREEN
15: TURQUOISE
35: TURQUOISE
16: DARK_RED
37: DARK_RED
40: SKY_BLUE
61: PLUM
25: PLUM
22: GREY_25_PERCENT
45: ROSE
43: LIGHT_YELLOW
42: LIGHT_GREEN
41: LIGHT_TURQUOISE
27:LIGHT_TURQUOISE
44: PALE_BLUE
46: LAVENDER
9: WHITE
24: CORNFLOWER_BLUE
26: LEMON_CHIFFON
25: MAROON
28: ORCHID
29: CORAL
30: ROYAL_BLUE
31: LIGHT_CORNFLOWER_BLUE
*/
//----------------------------------------------------你可以按上面的方法来自定义颜色
/*
* 自定义颜色,去掉注释,贴加,其他则查看颜色对照表
HSSFPalette palette = this.getCustomPalette();
palette.setColorAtIndex(idx,
i, //RGB red (0-255)
j, //RGB green
k //RGB blue
);
*/
//-------------------------------------------------
程序用例:
读取excel
public class ReaderExcelForIterateRowsAndCells {
/***
* 读xls格式的文档,Iteraotr遍历
*/
public void readXls(){
try {
FileInputStream fis = new FileInputStream("src/workbook.xls");
Workbook wb = WorkbookFactory.create(fis);
Sheet sheet = wb.getSheetAt(0);
for (Iterator<?> rit = sheet.rowIterator(); rit.hasNext(); ) {
Row row = (Row)rit.next();
for (Iterator<?> cit = row.cellIterator(); cit.hasNext(); ) {
Cell cell = (Cell)cit.next();
System.out.println(cell);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (InvalidFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/***
* 读xls格式的文档,for循环
*/
public void readXlsForEach(){
FileInputStream fis;
try {
fis = new FileInputStream("src/workbook.xls");
Workbook wb = WorkbookFactory.create(fis);
Sheet sheet = wb.getSheetAt(0);
for (Row row : sheet) {
for (Cell cell : row) {
System.out.println(cell);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (InvalidFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
ReaderExcelForIterateRowsAndCells reader = new ReaderExcelForIterateRowsAndCells();
//reader.readXls();
reader.readXlsForEach();
}
}
核心提示:设置字体
=========================================================================================================
public class CreateExcelForWorkingFontsSize {
/***
* 创建空的xls格式的文档,设置字体大小
*/
public void createXlsForFontsSize(){
Workbook wb = new HSSFWorkbook();
Sheet sheet = wb.createSheet("new sheet");
Row row = sheet.createRow(1);
// 创建字体并改变它
Font font = wb.createFont();
//设置长度
font.setFontHeightInPoints((short)24);
font.setFontName("Courier New");
//斜体
font.setItalic(true);
//设置字体杠杠
font.setStrikeout(true);
CellStyle style = wb.createCellStyle();
style.setFont(font);
Cell cell = row.createCell(1);
cell.setCellValue("This is a test of fonts");
cell.setCellStyle(style);
FileOutputStream fileOut = null;
try {
fileOut = new FileOutputStream("src/workbook.xls");
wb.write(fileOut);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(null !=fileOut){
fileOut.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
CreateExcelForWorkingFontsSize create = new CreateExcelForWorkingFontsSize();
create.createXlsForFontsSize();
}
}
apache common-poi之创建cell边框
=======================================================================================================
public class CreateExcelForCreateBordersCells {
/***
* 创建空的xls格式的文档,创建cell边框
*/
public void createXls(){
Workbook wb = new HSSFWorkbook();
Sheet sheet = wb.createSheet("new sheet");
Row row = sheet.createRow(1);
Cell cell = row.createCell(1);
cell.setCellValue(4);
//设置cell边框
CellStyle style = wb.createCellStyle();
//下边框
style.setBorderBottom(CellStyle.BORDER_THIN);
style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
//左边框
style.setBorderLeft(CellStyle.BORDER_THIN);
style.setLeftBorderColor(IndexedColors.GREEN.getIndex());
//右边框
style.setBorderRight(CellStyle.BORDER_THIN);
style.setRightBorderColor(IndexedColors.BLUE.getIndex());
//上边框
style.setBorderTop(CellStyle.BORDER_MEDIUM_DASHED);
style.setTopBorderColor(IndexedColors.BLACK.getIndex());
cell.setCellStyle(style);
FileOutputStream fileOut = null;
try {
fileOut = new FileOutputStream("src/workbook.xls");
wb.write(fileOut);
fileOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(null != fileOut){
fileOut.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
CreateExcelForCreateBordersCells create = new CreateExcelForCreateBordersCells();
create.createXls();
}
}
核心提示:创建不同的cells
================================================================================================
public class CreateExcelForCreateDifferentCells {
/***
* 创建空的xls格式的文档,创建不同的cells的内容
*/
public void createXls(){
Workbook wb = new HSSFWorkbook();
Sheet sheet = wb.createSheet("new sheet");
Row row = sheet.createRow((short)2);
row.createCell(0).setCellValue(1.1);
row.createCell(1).setCellValue(new Date());
row.createCell(2).setCellValue(Calendar.getInstance());
row.createCell(3).setCellValue("a string");
row.createCell(4).setCellValue(true);
row.createCell(5).setCellType(HSSFCell.CELL_TYPE_ERROR);
FileOutputStream fileOut = null;
try {
fileOut = new FileOutputStream("src/workbook.xls");
wb.write(fileOut);
fileOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(null != fileOut){
fileOut.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
CreateExcelForCreateDifferentCells create = new CreateExcelForCreateDifferentCells();
create.createXls();
}
}
核心提示:创建日期cells
================================================================================================
public class CreateExcelForCreateDateCells {
/***
* 创建空的xls格式的文档,并根据行号创建cell,创建日期格式
*/
public void createXlsForDateCell(){
Workbook wb = new HSSFWorkbook();
//创建的帮助类
CreationHelper createHelper = wb.getCreationHelper();
//cell样式
CellStyle cellStyle = wb.createCellStyle();
Sheet sheet = wb.createSheet("new sheet");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
//直接NEW出来的日期.
cell.setCellValue(new Date());
//经过样式处理过的日期
cellStyle.setDataFormat(createHelper.createDataFormat().getFormat("m/d/yy h:mm"));
cell = row.createCell(1);
cell.setCellValue(new Date());
cell.setCellStyle(cellStyle);
// cell = row.createCell(2);
// cell.setCellValue(Calendar.getInstance());
// cell.setCellStyle(cellStyle);
FileOutputStream fileOut;
try {
fileOut = new FileOutputStream("src/workbook1.xls");
wb.write(fileOut);
fileOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
CreateExcelForCreateDateCells create = new CreateExcelForCreateDateCells();
create.createXlsForDateCell();
}
}
核心提示:创建cells
==============================================================================================
public class CreateExcelForCreateCells {
/***
* 创建空的xls格式的文档,并根据行号创建cell并且赋值
*/
public void createXlsForCell(){
Workbook wb = new HSSFWorkbook();
CreationHelper createHelper = wb.getCreationHelper();
Sheet sheet = wb.createSheet("new sheet");
//创建行,并在第几行创建
Row row = sheet.createRow(1);
//创建行cells,初始值为0.
Cell cell = row.createCell(0);
//开始赋值
cell.setCellValue(1);
row.createCell(1).setCellValue(1.2);
row.createCell(2).setCellValue(createHelper.createRichTextString("1111111"));
row.createCell(3).setCellValue(111);
FileOutputStream fileOut = null;
try {
fileOut = new FileOutputStream("src/workbook.xls");
wb.write(fileOut);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(null != fileOut){
fileOut.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
CreateExcelForCreateCells create = new CreateExcelForCreateCells();
create.createXlsForCell();
}
}
apache common-poi之创建sheet
==============================================================================================
public class CreateExcelForNewSheet {
/***
* 创建空的xls格式的文档,创建sheet
*/
public void createXls(){
Workbook wb = new HSSFWorkbook();
FileOutputStream fileOut = null;
try {
fileOut = new FileOutputStream("src/workbook.xls");
wb.createSheet("create 1");
wb.createSheet("create 2");
wb.write(fileOut);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(null != fileOut){
fileOut.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
CreateExcelForNewSheet create = new CreateExcelForNewSheet();
create.createXls();
}
}
核心提示:创建excel
==============================================================================================
public class CreateExcel {
/***
* 创建xls格式的文档,创建xlsx,只需修改后缀
*/
public void createXls(){
Workbook wb = new HSSFWorkbook();
FileOutputStream fileOut = null;
try {
fileOut = new FileOutputStream("src/workbook.xls");
wb.write(fileOut);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(null != fileOut){
fileOut.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
CreateExcel create = new CreateExcel();
create.createXls();
}
}