POI学习笔记 自定义颜色

http://yunzhongxia.iteye.com/blog/561425

http://yunzhongxia.iteye.com/blog/558998

项目中经常要解析和生成Excel文件,最常用的开源组件有poi与jxl。jxl是韩国人开发的,发行较早,但是更新的很慢,目前似乎还不支持excel2007。poi是apache下的一个子项目,poi应该是处理ms的office系列文档最好的组件了。poi3.6版本已经开始支持excel2007了。但是由于excel2007底层的实现似乎变成xml与excel2003底层存储发生了本质的变化,因此poi解析excel的类就存在差异了。

      现在简单的介绍下poi常用的接口。

      经常用的类一般都在org.apache.poi.hssf.usermodel(excel2003)或org.apache.poi.xssf.usermodel
(excel2007)。

  • 工作薄:  WorkBook是操作Excel的入口,HSSFWorkbook, XSSFWorkbook实现了该接口。
  • 页:Sheet表示工作薄的分页。HSSFSheet, XSSFChartSheet, XSSFDialogsheet, XSSFSheet实现了该接口。
  • Row:表示页中的一行。HSSFRow, XSSFRow实现了该接口。
  • Cell:行中的一个单元格。HSSFCell, XSSFCell实现了该接口。

从上面的介绍得知:页是通过工作薄对象创建的,行是通过页对象创建的,单元格是通过行对象创建的。接下来,我们就开始发掘poi的强大功能吧。

  1. 创建一个空白的工作薄
Java代码 复制代码  收藏代码
  1. import java.io.FileOutputStream;   
  2. import org.apache.poi.hssf.usermodel.HSSFWorkbook;   
  3. import org.apache.poi.ss.usermodel.Workbook;   
  4. import org.apache.poi.xssf.usermodel.XSSFWorkbook;   
  5.   
  6. //2003版本   
  7. Workbook wb = new HSSFWorkbook();   
  8. FileOutputStream fileOut = new FileOutputStream("workbook.xls");   
  9. wb.write(fileOut);   
  10.  fileOut.close();   
  11.   
  12. //2007版本   
  13. // Workbook wb = new XSSFWorkbook();   
  14. // FileOutputStream fileOut = new FileOutputStrea("workbook.xlsx");   
  15. // wb.write(fileOut);   
  16. // fileOut.close();  
import java.io.FileOutputStream;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

//2003版本
Workbook wb = new HSSFWorkbook();
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
 fileOut.close();

//2007版本
// Workbook wb = new XSSFWorkbook();
// FileOutputStream fileOut = new FileOutputStrea("workbook.xlsx");
// wb.write(fileOut);
// fileOut.close();

 注意:Workbook 是org.apache.poi.ss.usermodel包下的一个接口,注意与以前版本的不同,HSSFWorkbook和XSSFWorkbook实现了该接口,这样就达到了面前接口编程。下面的excel工具类中要用到此点知识。

 2. 创建两个空白页

 

 

Java代码 复制代码  收藏代码
  1. Workbook wb = new HSSFWorkbook();   
  2. //Workbook wb = new XSSFWorkbook();   
  3. Sheet sheet1 = wb.createSheet("new sheet");   
  4. Sheet sheet2 = wb.createSheet("second sheet");   
  5. FileOutputStream fileOut = new FileOutputStream("workbook.xls");   
  6. wb.write(fileOut);   
  7. fileOut.close();  
Workbook wb = new HSSFWorkbook();
//Workbook wb = new XSSFWorkbook();
Sheet sheet1 = wb.createSheet("new sheet");
Sheet sheet2 = wb.createSheet("second sheet");
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();

 

3. 创建单元格

 

Java代码 复制代码  收藏代码
  1. public void createRow() throws Exception {   
  2.         Workbook wb = new HSSFWorkbook();   
  3.         // Workbook wb = new XSSFWorkbook();   
  4.         CreationHelper createHelper = wb.getCreationHelper();   
  5.         Sheet sheet = wb.createSheet("new sheet");   
  6.   
  7.         //创建一行并放一些单元格到该行中,行的索引是以0开始的   
  8.         Row row = sheet.createRow((short0);   
  9.         // 创建一个单元格并填充一个整数的值   
  10.         Cell cell = row.createCell(0);   
  11.         cell.setCellValue(1);   
  12.   
  13.         //链式写法   
  14.         row.createCell(1).setCellValue(1.2);   
  15.         row.createCell(2).setCellValue(   
  16.                 createHelper.createRichTextString("This is a string"));   
  17.         row.createCell(3).setCellValue(true);   
  18.   
  19.         //输出文件   
  20.         FileOutputStream fileOut = new FileOutputStream("workbook.xls");   
  21.         wb.write(fileOut);   
  22.         fileOut.close();   
  23.   
  24.     }  
public void createRow() throws Exception {
		Workbook wb = new HSSFWorkbook();
		// Workbook wb = new XSSFWorkbook();
		CreationHelper createHelper = wb.getCreationHelper();
		Sheet sheet = wb.createSheet("new sheet");

		//创建一行并放一些单元格到该行中,行的索引是以0开始的
		Row row = sheet.createRow((short) 0);
		// 创建一个单元格并填充一个整数的值
		Cell cell = row.createCell(0);
		cell.setCellValue(1);

		//链式写法
		row.createCell(1).setCellValue(1.2);
		row.createCell(2).setCellValue(
				createHelper.createRichTextString("This is a string"));
		row.createCell(3).setCellValue(true);

		//输出文件
		FileOutputStream fileOut = new FileOutputStream("workbook.xls");
		wb.write(fileOut);
		fileOut.close();

	}

 

 4. 创建日期单元格

 

Java代码 复制代码  收藏代码
  1. public void createDateCell() throws Exception {   
  2.         Workbook wb = new HSSFWorkbook();   
  3.         // Workbook wb = new XSSFWorkbook();   
  4.         CreationHelper createHelper = wb.getCreationHelper();   
  5.         Sheet sheet = wb.createSheet("new sheet");   
  6.   
  7.         // Create a row and put some cells in it. Rows are 0 based.   
  8.         Row row = sheet.createRow(0);   
  9.   
  10.         // Create a cell and put a date value in it. The first cell is not   
  11.         // styled   
  12.         // as a date.   
  13.         Cell cell = row.createCell(0);   
  14.         cell.setCellValue(new Date());   
  15.   
  16.         // we style the second cell as a date (and time). It is important to   
  17.         // create a new cell style from the workbook otherwise you can end up   
  18.         // modifying the built in style and effecting not only this cell but   
  19.         // other cells.   
  20.         CellStyle cellStyle = wb.createCellStyle();   
  21.         cellStyle.setDataFormat(createHelper.createDataFormat().getFormat(   
  22.                 "yyyy/MM/dd hh:mm"));   
  23.         cell = row.createCell(1);   
  24.         // cell.setCellValue(new Date());   
  25.         Date date = new Date();   
  26.   
  27.         cell.setCellValue(createHelper.createRichTextString(date.toString()));   
  28.         cell.setCellStyle(cellStyle);   
  29.   
  30.         // you can also set date as java.util.Calendar   
  31.         cell = row.createCell(2);   
  32.         cell.setCellValue(Calendar.getInstance());   
  33.         cell.setCellStyle(cellStyle);   
  34.   
  35.         // Write the output to a file   
  36.         FileOutputStream fileOut = new FileOutputStream("workbook.xls");   
  37.         wb.write(fileOut);   
  38.         fileOut.close();   
  39.   
  40.     }  
public void createDateCell() throws Exception {
		Workbook wb = new HSSFWorkbook();
		// Workbook wb = new XSSFWorkbook();
		CreationHelper createHelper = wb.getCreationHelper();
		Sheet sheet = wb.createSheet("new sheet");

		// Create a row and put some cells in it. Rows are 0 based.
		Row row = sheet.createRow(0);

		// Create a cell and put a date value in it. The first cell is not
		// styled
		// as a date.
		Cell cell = row.createCell(0);
		cell.setCellValue(new Date());

		// we style the second cell as a date (and time). It is important to
		// create a new cell style from the workbook otherwise you can end up
		// modifying the built in style and effecting not only this cell but
		// other cells.
		CellStyle cellStyle = wb.createCellStyle();
		cellStyle.setDataFormat(createHelper.createDataFormat().getFormat(
				"yyyy/MM/dd hh:mm"));
		cell = row.createCell(1);
		// cell.setCellValue(new Date());
		Date date = new Date();

		cell.setCellValue(createHelper.createRichTextString(date.toString()));
		cell.setCellStyle(cellStyle);

		// you can also set date as java.util.Calendar
		cell = row.createCell(2);
		cell.setCellValue(Calendar.getInstance());
		cell.setCellStyle(cellStyle);

		// Write the output to a file
		FileOutputStream fileOut = new FileOutputStream("workbook.xls");
		wb.write(fileOut);
		fileOut.close();

	}

 

5.  创建不同的单元格样式

 

Java代码 复制代码  收藏代码
  1. public void createCellType() throws Exception{   
  2.         Workbook wb = new HSSFWorkbook();   
  3.         Sheet sheet = wb.createSheet("new sheet");   
  4.         Row row = sheet.createRow((short)2);   
  5.         row.createCell(0).setCellValue(1.1);   
  6.         row.createCell(1).setCellValue(new Date());   
  7.         row.createCell(2).setCellValue(Calendar.getInstance());   
  8.         row.createCell(3).setCellValue("a string");   
  9.         row.createCell(4).setCellValue(true);   
  10.         row.createCell(5).setCellType(HSSFCell.CELL_TYPE_ERROR);   
  11.   
  12.         // Write the output to a file   
  13.         FileOutputStream fileOut = new FileOutputStream("workbook.xls");   
  14.         wb.write(fileOut);   
  15.         fileOut.close();   
  16.     }  
public void createCellType() throws Exception{
		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);

	    // Write the output to a file
	    FileOutputStream fileOut = new FileOutputStream("workbook.xls");
	    wb.write(fileOut);
	    fileOut.close();
	}

 

6.  设置单元格水平垂直对齐方式

 

Java代码 复制代码  收藏代码
  1. public static void main(String[] args)  throws Exception {   
  2.         Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();   
  3.   
  4.         Sheet sheet = wb.createSheet();   
  5.         Row row = sheet.createRow((short2);   
  6.         row.setHeightInPoints(30);   
  7.   
  8.         createCell(wb, row, (short0, XSSFCellStyle.ALIGN_CENTER, XSSFCellStyle.VERTICAL_BOTTOM);   
  9.         createCell(wb, row, (short1, XSSFCellStyle.ALIGN_CENTER_SELECTION, XSSFCellStyle.VERTICAL_BOTTOM);   
  10.         createCell(wb, row, (short2, XSSFCellStyle.ALIGN_FILL, XSSFCellStyle.VERTICAL_CENTER);   
  11.         createCell(wb, row, (short3, XSSFCellStyle.ALIGN_GENERAL, XSSFCellStyle.VERTICAL_CENTER);   
  12.         createCell(wb, row, (short4, XSSFCellStyle.ALIGN_JUSTIFY, XSSFCellStyle.VERTICAL_JUSTIFY);   
  13.         createCell(wb, row, (short5, XSSFCellStyle.ALIGN_LEFT, XSSFCellStyle.VERTICAL_TOP);   
  14.         createCell(wb, row, (short6, XSSFCellStyle.ALIGN_RIGHT, XSSFCellStyle.VERTICAL_TOP);   
  15.   
  16.         // Write the output to a file   
  17.         FileOutputStream fileOut = new FileOutputStream("xssf-align.xlsx");   
  18.         wb.write(fileOut);   
  19.         fileOut.close();   
  20.   
  21.     }   
  22.   
  23.     /**  
  24.      * Creates a cell and aligns it a certain way.  
  25.      *  
  26.      * @param wb     the workbook  
  27.      * @param row    the row to create the cell in  
  28.      * @param column the column number to create the cell in  
  29.      * @param halign the horizontal alignment for the cell.  
  30.      */  
  31.     private static void createCell(Workbook wb, Row row, short column, short halign, short valign) {   
  32.         Cell cell = row.createCell(column);   
  33.         cell.setCellValue(new XSSFRichTextString("Align It"));   
  34.         CellStyle cellStyle = wb.createCellStyle();   
  35.         cellStyle.setAlignment(halign);   
  36.         cellStyle.setVerticalAlignment(valign);   
  37.         cell.setCellStyle(cellStyle);   
  38.     }  

 

7.  设置单元格的边框

 

Java代码 复制代码  收藏代码
  1. public void createBorder() throws Exception {   
  2.         Workbook wb = new HSSFWorkbook();   
  3.         Sheet sheet = wb.createSheet("new sheet");   
  4.   
  5.         // Create a row and put some cells in it. Rows are 0 based.   
  6.         Row row = sheet.createRow(1);   
  7.   
  8.         // Create a cell and put a value in it.   
  9.         Cell cell = row.createCell(1);   
  10.         cell.setCellValue(4);   
  11.   
  12.         // Style the cell with borders all around.   
  13.         CellStyle style = wb.createCellStyle();   
  14.         style.setBorderBottom(CellStyle.BORDER_THIN);   
  15.         style.setBottomBorderColor(IndexedColors.BLACK.getIndex());   
  16.         style.setBorderLeft(CellStyle.BORDER_THIN);   
  17.         style.setLeftBorderColor(IndexedColors.GREEN.getIndex());   
  18.         style.setBorderRight(CellStyle.BORDER_THIN);   
  19.         style.setRightBorderColor(IndexedColors.BLUE.getIndex());   
  20.         style.setBorderTop(CellStyle.BORDER_MEDIUM_DASHED);   
  21.         style.setTopBorderColor(IndexedColors.BLACK.getIndex());   
  22.         cell.setCellStyle(style);   
  23.   
  24.         // Write the output to a file   
  25.         FileOutputStream fileOut = new FileOutputStream("workbook.xls");   
  26.         wb.write(fileOut);   
  27.         fileOut.close();   
  28.   
  29.     }  
public void createBorder() throws Exception {
		Workbook wb = new HSSFWorkbook();
		Sheet sheet = wb.createSheet("new sheet");

		// Create a row and put some cells in it. Rows are 0 based.
		Row row = sheet.createRow(1);

		// Create a cell and put a value in it.
		Cell cell = row.createCell(1);
		cell.setCellValue(4);

		// Style the cell with borders all around.
		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);

		// Write the output to a file
		FileOutputStream fileOut = new FileOutputStream("workbook.xls");
		wb.write(fileOut);
		fileOut.close();

	}

 

8. 迭代行和单元格

 

    有时需要迭代一个页中的所有行,或者一个行中所有的单元格。一个简单的方法是循环。

    幸运的是,poi知道我们所需。页可以通过sheet.rowIterator()迭代出所有的行,行可以通过row.cellIterator()迭代出所有的单元格。总之,Sheet和Row实现了java.lang.Iterable,如果你用的是jdk1.5以上的版本,你可以使用java高级for循环。

 

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.     }  
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();
			// Do something here
		}
	}
					HSSFSheet sheet = wb.getSheetAt(0);
	for (Iterator<HSSFRow> rit = (Iterator<HSSFRow>)sheet.rowIterator(); rit.hasNext(); ) {
		HSSFRow row = rit.next();
		for (Iterator<HSSFCell> cit = (Iterator<HSSFCell>)row.cellIterator(); cit.hasNext(); ) {
			HSSFCell cell = cit.next();
			// Do something here
		}
	}

 

java高级for循环迭代行和单元格

 

Java代码 复制代码  收藏代码
  1. Sheet sheet = wb.getSheetAt(0);   
  2.     for (Row row : sheet) {   
  3.         for (Cell cell : row) {   
  4.             // Do something here   
  5.         }   
  6.     }  
Sheet sheet = wb.getSheetAt(0);
	for (Row row : sheet) {
		for (Cell cell : row) {
			// Do something here
		}
	}

 

9.  得到单元格的内容

 

     想得到单元格的内容之前,首先要知道单元格的类型,因此你要先判断单元格的类型之后选择合适的方法得到单元格的值。下面的代码,循环得到一个Sheet所有的单元格。

 

Java代码 复制代码  收藏代码
  1. public void getCellValue() throws Exception {   
  2.         InputStream inp = new FileInputStream("D:\\hjn.xls");   
  3.         HSSFWorkbook wb = new HSSFWorkbook(new POIFSFileSystem(inp));   
  4.         Sheet sheet1 = wb.getSheetAt(0);   
  5.         for (Row row : sheet1) {   
  6.             for (Cell cell : row) {   
  7.                 CellReference cellRef = new CellReference(row.getRowNum(), cell   
  8.                         .getColumnIndex());   
  9.                 System.out.print(cellRef.formatAsString());   
  10.                 System.out.print(" - ");   
  11.   
  12.                 switch (cell.getCellType()) {   
  13.                 case Cell.CELL_TYPE_STRING:   
  14.                     System.out.println(cell.getRichStringCellValue()   
  15.                             .getString());   
  16.                     break;   
  17.                 case Cell.CELL_TYPE_NUMERIC:   
  18.                     if (DateUtil.isCellDateFormatted(cell)) {   
  19.                         System.out.println(cell.getDateCellValue());   
  20.                     } else {   
  21.                         System.out.println(cell.getNumericCellValue());   
  22.                     }   
  23.                     break;   
  24.                 case Cell.CELL_TYPE_BOOLEAN:   
  25.                     System.out.println(cell.getBooleanCellValue());   
  26.                     break;   
  27.                 case Cell.CELL_TYPE_FORMULA:   
  28.                     System.out.println(cell.getCellFormula());   
  29.                     break;   
  30.                 default:   
  31.                     System.out.println();   
  32.                 }   
  33.             }   
  34.         }   
  35.   
  36.     }  
public void getCellValue() throws Exception {
		InputStream inp = new FileInputStream("D:\\hjn.xls");
		HSSFWorkbook wb = new HSSFWorkbook(new POIFSFileSystem(inp));
		Sheet sheet1 = wb.getSheetAt(0);
		for (Row row : sheet1) {
			for (Cell cell : row) {
				CellReference cellRef = new CellReference(row.getRowNum(), cell
						.getColumnIndex());
				System.out.print(cellRef.formatAsString());
				System.out.print(" - ");

				switch (cell.getCellType()) {
				case Cell.CELL_TYPE_STRING:
					System.out.println(cell.getRichStringCellValue()
							.getString());
					break;
				case Cell.CELL_TYPE_NUMERIC:
					if (DateUtil.isCellDateFormatted(cell)) {
						System.out.println(cell.getDateCellValue());
					} else {
						System.out.println(cell.getNumericCellValue());
					}
					break;
				case Cell.CELL_TYPE_BOOLEAN:
					System.out.println(cell.getBooleanCellValue());
					break;
				case Cell.CELL_TYPE_FORMULA:
					System.out.println(cell.getCellFormula());
					break;
				default:
					System.out.println();
				}
			}
		}

	}

 

10. 文本提取

 

poi的ExcelExtractor可以抽取Cell中的值。org.apache.poi.ss.extractor 为抽取类的接口,ExcelExtractor, XSSFExcelExtractor实现了该接口。

 

Java代码 复制代码  收藏代码
  1. InputStream inp = new FileInputStream("D:\\hjn.xls");   
  2.         HSSFWorkbook  wb = new HSSFWorkbook(new POIFSFileSystem(inp));   
  3.            
  4.         ExcelExtractor extractor = new ExcelExtractor(wb);   
  5.   
  6.         extractor.setFormulasNotResults(true);   
  7.         extractor.setIncludeSheetNames(true);   
  8.         String text = extractor.getText();   
  9.         System.out.println(text);  
InputStream inp = new FileInputStream("D:\\hjn.xls");
		HSSFWorkbook  wb = new HSSFWorkbook(new POIFSFileSystem(inp));
		
		ExcelExtractor extractor = new ExcelExtractor(wb);

		extractor.setFormulasNotResults(true);
		extractor.setIncludeSheetNames(true);
		String text = extractor.getText();
		System.out.println(text);

 

 11. 填充和颜色

 

Java代码 复制代码  收藏代码
  1. public void fillAndColors() throws Exception{   
  2.         Workbook wb = new HSSFWorkbook();   
  3.         Sheet sheet = wb.createSheet("new sheet");   
  4.   
  5.         // Create a row and put some cells in it. Rows are 0 based.   
  6.         Row row = sheet.createRow((short1);   
  7.   
  8.         // Aqua background   
  9.         CellStyle style = wb.createCellStyle();   
  10.         style.setFillBackgroundColor(IndexedColors.BLUE.getIndex());   
  11.         style.setFillPattern(CellStyle.ALIGN_FILL);   
  12.         Cell cell = row.createCell((short1);   
  13.         cell.setCellValue("X");   
  14.         cell.setCellStyle(style);   
  15.   
  16.         // Orange "foreground", foreground being the fill foreground not the font color.   
  17.         style = wb.createCellStyle();   
  18.         style.setFillForegroundColor(IndexedColors.ORANGE.getIndex());   
  19.         style.setFillPattern(CellStyle.SOLID_FOREGROUND);   
  20.         cell = row.createCell((short2);   
  21.         cell.setCellValue("X");   
  22.         cell.setCellStyle(style);   
  23.   
  24.         // Write the output to a file   
  25.         FileOutputStream fileOut = new FileOutputStream("workbook.xls");   
  26.         wb.write(fileOut);   
  27.         fileOut.close();   
  28.   
  29.     }  
public void fillAndColors() throws Exception{
		Workbook wb = new HSSFWorkbook();
	    Sheet sheet = wb.createSheet("new sheet");

	    // Create a row and put some cells in it. Rows are 0 based.
	    Row row = sheet.createRow((short) 1);

	    // Aqua background
	    CellStyle style = wb.createCellStyle();
	    style.setFillBackgroundColor(IndexedColors.BLUE.getIndex());
	    style.setFillPattern(CellStyle.ALIGN_FILL);
	    Cell cell = row.createCell((short) 1);
	    cell.setCellValue("X");
	    cell.setCellStyle(style);

	    // Orange "foreground", foreground being the fill foreground not the font color.
	    style = wb.createCellStyle();
	    style.setFillForegroundColor(IndexedColors.ORANGE.getIndex());
	    style.setFillPattern(CellStyle.SOLID_FOREGROUND);
	    cell = row.createCell((short) 2);
	    cell.setCellValue("X");
	    cell.setCellStyle(style);

	    // Write the output to a file
	    FileOutputStream fileOut = new FileOutputStream("workbook.xls");
	    wb.write(fileOut);
	    fileOut.close();

	}

 

12. 合并单元格

 

Java代码 复制代码  收藏代码
  1. public void mergingCell() throws Exception{   
  2.         Workbook wb = new HSSFWorkbook();   
  3.         Sheet sheet = wb.createSheet("new sheet");   
  4.         Row row = sheet.createRow((short1);   
  5.         Cell cell = row.createCell((short1);   
  6.         cell.setCellValue("This is a test of merging");   
  7.   
  8.         sheet.addMergedRegion(new CellRangeAddress(1// first row (0-based)   
  9.                 4// last row (0-based)   
  10.                 1// first column (0-based)   
  11.                 6 // last column (0-based)   
  12.                 ));   
  13.   
  14.         // Write the output to a file   
  15.         FileOutputStream fileOut = new FileOutputStream("workbook.xls");   
  16.         wb.write(fileOut);   
  17.         fileOut.close();   
  18.   
  19.     }  
public void mergingCell() throws Exception{
		Workbook wb = new HSSFWorkbook();
		Sheet sheet = wb.createSheet("new sheet");
		Row row = sheet.createRow((short) 1);
		Cell cell = row.createCell((short) 1);
		cell.setCellValue("This is a test of merging");

		sheet.addMergedRegion(new CellRangeAddress(1, // first row (0-based)
				4, // last row (0-based)
				1, // first column (0-based)
				6 // last column (0-based)
				));

		// Write the output to a file
		FileOutputStream fileOut = new FileOutputStream("workbook.xls");
		wb.write(fileOut);
		fileOut.close();

	}

 

13. 设置字体

 

Java代码 复制代码  收藏代码
  1. public void createFont() throws Exception{   
  2.         Workbook wb = new HSSFWorkbook();   
  3.         Sheet sheet = wb.createSheet("new sheet");   
  4.   
  5.         // Create a row and put some cells in it. Rows are 0 based.   
  6.         Row row = sheet.createRow(1);   
  7.   
  8.         // Create a new font and alter it.   
  9.         Font font = wb.createFont();   
  10.         font.setFontHeightInPoints((short)24);   
  11.         font.setFontName("Courier New");   
  12.         font.setItalic(true);   
  13.         font.setStrikeout(true);   
  14.   
  15.         // Fonts are set into a style so create a new one to use.   
  16.         CellStyle style = wb.createCellStyle();   
  17.         style.setFont(font);   
  18.   
  19.         // Create a cell and put a value in it.   
  20.         Cell cell = row.createCell(1);   
  21.         cell.setCellValue("This is a test of fonts");   
  22.         cell.setCellStyle(style);   
  23.   
  24.         // Write the output to a file   
  25.         FileOutputStream fileOut = new FileOutputStream("workbook.xls");   
  26.         wb.write(fileOut);   
  27.         fileOut.close();   
  28.   
  29.     }  
public void createFont() throws Exception{
		Workbook wb = new HSSFWorkbook();
	    Sheet sheet = wb.createSheet("new sheet");

	    // Create a row and put some cells in it. Rows are 0 based.
	    Row row = sheet.createRow(1);

	    // Create a new font and alter it.
	    Font font = wb.createFont();
	    font.setFontHeightInPoints((short)24);
	    font.setFontName("Courier New");
	    font.setItalic(true);
	    font.setStrikeout(true);

	    // Fonts are set into a style so create a new one to use.
	    CellStyle style = wb.createCellStyle();
	    style.setFont(font);

	    // Create a cell and put a value in it.
	    Cell cell = row.createCell(1);
	    cell.setCellValue("This is a test of fonts");
	    cell.setCellStyle(style);

	    // Write the output to a file
	    FileOutputStream fileOut = new FileOutputStream("workbook.xls");
	    wb.write(fileOut);
	    fileOut.close();

	}

 

注意:一个工作薄最多只能创建32767 个不同的字体样式,因此你应该重用字体样式而不应该每创建一个单元格就创建一个单元格字体样式。

错误写法:

 

Java代码 复制代码  收藏代码
  1. for (int i = 0; i < 10000; i++) {   
  2.           Row row = sheet.createRow(i);   
  3.           Cell cell = row.createCell((short0);   
  4.   
  5.           CellStyle style = workbook.createCellStyle();   
  6.           Font font = workbook.createFont();   
  7.           font.setBoldweight(Font.BOLDWEIGHT_BOLD);   
  8.           style.setFont(font);   
  9.           cell.setCellStyle(style);   
  10.       }  
  for (int i = 0; i < 10000; i++) {
            Row row = sheet.createRow(i);
            Cell cell = row.createCell((short) 0);

            CellStyle style = workbook.createCellStyle();
            Font font = workbook.createFont();
            font.setBoldweight(Font.BOLDWEIGHT_BOLD);
            style.setFont(font);
            cell.setCellStyle(style);
        }

 
正确写法:

 

Java代码
CellStyle style = workbook.createCellStyle();   
  1. Font font = workbook.createFont();   
  2. font.setBoldweight(Font.BOLDWEIGHT_BOLD);   
  3. style.setFont(font);   
  4. for (int i = 0; i < 10000; i++) {   
  5.     Row row = sheet.createRow(i);   
  6.     Cell cell = row.createCell((short0);   
  7.     cell.setCellStyle(style);   
  8. }  

 

14. 自定义颜色

      HSSF:

 

Java代码 复制代码  收藏代码
  1. HSSFWorkbook wb = new HSSFWorkbook();   
  2.     HSSFSheet sheet = wb.createSheet();   
  3.     HSSFRow row = sheet.createRow((short0);   
  4.     HSSFCell cell = row.createCell((short0);   
  5.     cell.setCellValue("Default Palette");   
  6.   
  7.     //apply some colors from the standard palette,   
  8.     // as in the previous examples.   
  9.     //we'll use red text on a lime background   
  10.   
  11.     HSSFCellStyle style = wb.createCellStyle();   
  12.     style.setFillForegroundColor(HSSFColor.LIME.index);   
  13.     style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);   
  14.   
  15.     HSSFFont font = wb.createFont();   
  16.     font.setColor(HSSFColor.RED.index);   
  17.     style.setFont(font);   
  18.   
  19.     cell.setCellStyle(style);   
  20.   
  21.     //save with the default palette   
  22.     FileOutputStream out = new FileOutputStream("default_palette.xls");   
  23.     wb.write(out);   
  24.     out.close();   
  25.   
  26.     //now, let's replace RED and LIME in the palette   
  27.     // with a more attractive combination   
  28.     // (lovingly borrowed from freebsd.org)   
  29.   
  30.     cell.setCellValue("Modified Palette");   
  31.   
  32.     //creating a custom palette for the workbook   
  33.     HSSFPalette palette = wb.getCustomPalette();   
  34.   
  35.     //replacing the standard red with freebsd.org red   
  36.     palette.setColorAtIndex(HSSFColor.RED.index,   
  37.             (byte153,  //RGB red (0-255)   
  38.             (byte0,    //RGB green   
  39.             (byte0     //RGB blue   
  40.     );   
  41.     //replacing lime with freebsd.org gold   
  42.     palette.setColorAtIndex(HSSFColor.LIME.index, (byte255, (byte204, (byte102);   
  43.   
  44.     //save with the modified palette   
  45.     // note that wherever we have previously used RED or LIME, the   
  46.     // new colors magically appear   
  47.     out = new FileOutputStream("modified_palette.xls");   
  48.     wb.write(out);   
  49.     out.close();  
HSSFWorkbook wb = new HSSFWorkbook();
    HSSFSheet sheet = wb.createSheet();
    HSSFRow row = sheet.createRow((short) 0);
    HSSFCell cell = row.createCell((short) 0);
    cell.setCellValue("Default Palette");

    //apply some colors from the standard palette,
    // as in the previous examples.
    //we'll use red text on a lime background

    HSSFCellStyle style = wb.createCellStyle();
    style.setFillForegroundColor(HSSFColor.LIME.index);
    style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

    HSSFFont font = wb.createFont();
    font.setColor(HSSFColor.RED.index);
    style.setFont(font);

    cell.setCellStyle(style);

    //save with the default palette
    FileOutputStream out = new FileOutputStream("default_palette.xls");
    wb.write(out);
    out.close();

    //now, let's replace RED and LIME in the palette
    // with a more attractive combination
    // (lovingly borrowed from freebsd.org)

    cell.setCellValue("Modified Palette");

    //creating a custom palette for the workbook
    HSSFPalette palette = wb.getCustomPalette();

    //replacing the standard red with freebsd.org red
    palette.setColorAtIndex(HSSFColor.RED.index,
            (byte) 153,  //RGB red (0-255)
            (byte) 0,    //RGB green
            (byte) 0     //RGB blue
    );
    //replacing lime with freebsd.org gold
    palette.setColorAtIndex(HSSFColor.LIME.index, (byte) 255, (byte) 204, (byte) 102);

    //save with the modified palette
    // note that wherever we have previously used RED or LIME, the
    // new colors magically appear
    out = new FileOutputStream("modified_palette.xls");
    wb.write(out);
    out.close();

 

XSSF:

 

Java代码 复制代码  收藏代码
  1. XSSFWorkbook wb = new XSSFWorkbook();   
  2.     XSSFSheet sheet = wb.createSheet();   
  3.     XSSFRow row = sheet.createRow(0);   
  4.     XSSFCell cell = row.createCell( 0);   
  5.     cell.setCellValue("custom XSSF colors");   
  6.   
  7.     XSSFCellStyle style1 = wb.createCellStyle();   
  8.     style1.setFillForegroundColor(new XSSFColor(new java.awt.Color(1280128)));   
  9.     style1.setFillPattern(CellStyle.SOLID_FOREGROUND);  
XSSFWorkbook wb = new XSSFWorkbook();
    XSSFSheet sheet = wb.createSheet();
    XSSFRow row = sheet.createRow(0);
    XSSFCell cell = row.createCell( 0);
    cell.setCellValue("custom XSSF colors");

    XSSFCellStyle style1 = wb.createCellStyle();
    style1.setFillForegroundColor(new XSSFColor(new java.awt.Color(128, 0, 128)));
    style1.setFillPattern(CellStyle.SOLID_FOREGROUND);

 

 

15. 读取和重写工作薄

 

Java代码 复制代码  收藏代码
  1. InputStream inp = new FileInputStream("workbook.xls");   
  2.     //InputStream inp = new FileInputStream("workbook.xlsx");   
  3.   
  4.     Workbook wb = WorkbookFactory.create(inp);   
  5.     Sheet sheet = wb.getSheetAt(0);   
  6.     Row row = sheet.getRow(2);   
  7.     Cell cell = row.getCell(3);   
  8.     if (cell == null)   
  9.         cell = row.createCell(3);   
  10.     cell.setCellType(Cell.CELL_TYPE_STRING);   
  11.     cell.setCellValue("a test");   
  12.   
  13.     // Write the output to a file   
  14.     FileOutputStream fileOut = new FileOutputStream("workbook.xls");   
  15.     wb.write(fileOut);   
  16.     fileOut.close();   
  17.                       
InputStream inp = new FileInputStream("workbook.xls");
    //InputStream inp = new FileInputStream("workbook.xlsx");

    Workbook wb = WorkbookFactory.create(inp);
    Sheet sheet = wb.getSheetAt(0);
    Row row = sheet.getRow(2);
    Cell cell = row.getCell(3);
    if (cell == null)
        cell = row.createCell(3);
    cell.setCellType(Cell.CELL_TYPE_STRING);
    cell.setCellValue("a test");

    // Write the output to a file
    FileOutputStream fileOut = new FileOutputStream("workbook.xls");
    wb.write(fileOut);
    fileOut.close();
                    

 

 

16. 单元格内容换行

 

Java代码 复制代码  收藏代码
  1. Workbook wb = new XSSFWorkbook();   //or new HSSFWorkbook();   
  2.     Sheet sheet = wb.createSheet();   
  3.   
  4.     Row row = sheet.createRow(2);   
  5.     Cell cell = row.createCell(2);   
  6.     cell.setCellValue("Use \n with word wrap on to create a new line");   
  7.   
  8.     //to enable newlines you need set a cell styles with wrap=true   
  9.     CellStyle cs = wb.createCellStyle();   
  10.     cs.setWrapText(true);   
  11.     cell.setCellStyle(cs);   
  12.   
  13.     //increase row height to accomodate two lines of text   
  14.     row.setHeightInPoints((2*sheet.getDefaultRowHeightInPoints()));   
  15.   
  16.     //adjust column width to fit the content   
  17.     sheet.autoSizeColumn((short)2);   
  18.   
  19.     FileOutputStream fileOut = new FileOutputStream("ooxml-newlines.xlsx");   
  20.     wb.write(fileOut);   
  21.     fileOut.close();  
Workbook wb = new XSSFWorkbook();   //or new HSSFWorkbook();
    Sheet sheet = wb.createSheet();

    Row row = sheet.createRow(2);
    Cell cell = row.createCell(2);
    cell.setCellValue("Use \n with word wrap on to create a new line");

    //to enable newlines you need set a cell styles with wrap=true
    CellStyle cs = wb.createCellStyle();
    cs.setWrapText(true);
    cell.setCellStyle(cs);

    //increase row height to accomodate two lines of text
    row.setHeightInPoints((2*sheet.getDefaultRowHeightInPoints()));

    //adjust column width to fit the content
    sheet.autoSizeColumn((short)2);

    FileOutputStream fileOut = new FileOutputStream("ooxml-newlines.xlsx");
    wb.write(fileOut);
    fileOut.close();

 

 换行的步骤:

  • 在需要换行的地方加上\n   cell.setCellValue("Use \n with word wrap on to create a new line");
  • 设置行高 row.setHeightInPoints((2*sheet.getDefaultRowHeightInPoints()));
  • 设置列只适应宽度 sheet.autoSizeColumn((short)2);

 17. 数据格式化

 

Java代码 复制代码  收藏代码
  1. public void dataFormat() throws Exception{   
  2.         Workbook wb = new HSSFWorkbook();   
  3.         Sheet sheet = wb.createSheet("format sheet");   
  4.         CellStyle style;   
  5.         DataFormat format = wb.createDataFormat();   
  6.         Row row;   
  7.         Cell cell;   
  8.         short rowNum = 0;   
  9.         short colNum = 0;   
  10.   
  11.         row = sheet.createRow(rowNum++);   
  12.         cell = row.createCell(colNum);   
  13.         cell.setCellValue(11111.25);   
  14.         style = wb.createCellStyle();   
  15.         style.setDataFormat(format.getFormat("0.0"));   
  16.         cell.setCellStyle(style);   
  17.   
  18.         row = sheet.createRow(rowNum++);   
  19.         cell = row.createCell(colNum);   
  20.         cell.setCellValue(1111.25);   
  21.         style = wb.createCellStyle();   
  22.         style.setDataFormat(format.getFormat("#,###.0000"));   
  23.         cell.setCellStyle(style);   
  24.   
  25.         FileOutputStream fileOut = new FileOutputStream("workbook.xls");   
  26.         wb.write(fileOut);   
  27.         fileOut.close();   
  28.   
  29.     }  
public void dataFormat() throws Exception{
		Workbook wb = new HSSFWorkbook();
	    Sheet sheet = wb.createSheet("format sheet");
	    CellStyle style;
	    DataFormat format = wb.createDataFormat();
	    Row row;
	    Cell cell;
	    short rowNum = 0;
	    short colNum = 0;

	    row = sheet.createRow(rowNum++);
	    cell = row.createCell(colNum);
	    cell.setCellValue(11111.25);
	    style = wb.createCellStyle();
	    style.setDataFormat(format.getFormat("0.0"));
	    cell.setCellStyle(style);

	    row = sheet.createRow(rowNum++);
	    cell = row.createCell(colNum);
	    cell.setCellValue(1111.25);
	    style = wb.createCellStyle();
	    style.setDataFormat(format.getFormat("#,###.0000"));
	    cell.setCellStyle(style);

	    FileOutputStream fileOut = new FileOutputStream("workbook.xls");
	    wb.write(fileOut);
	    fileOut.close();

	}

 

18. 设置打印区域

 

Java代码 复制代码  收藏代码
  1. Workbook wb = new HSSFWorkbook();   
  2.     Sheet sheet = wb.createSheet("Sheet1");   
  3.     //sets the print area for the first sheet   
  4.     wb.setPrintArea(0"$A$1:$C$2");   
  5.        
  6.     //Alternatively:   
  7.     wb.setPrintArea(   
  8.             0//sheet index   
  9.             0//start column   
  10.             1//end column   
  11.             0//start row   
  12.             0  //end row   
  13.     );   
  14.   
  15.     FileOutputStream fileOut = new FileOutputStream("workbook.xls");   
  16.     wb.write(fileOut);   
  17.     fileOut.close();  
Workbook wb = new HSSFWorkbook();
    Sheet sheet = wb.createSheet("Sheet1");
    //sets the print area for the first sheet
    wb.setPrintArea(0, "$A$1:$C$2");
    
    //Alternatively:
    wb.setPrintArea(
            0, //sheet index
            0, //start column
            1, //end column
            0, //start row
            0  //end row
    );

    FileOutputStream fileOut = new FileOutputStream("workbook.xls");
    wb.write(fileOut);
    fileOut.close();

 

19. 设置页脚

 

   

Java代码 复制代码  收藏代码
  1. HSSFWorkbook wb = new HSSFWorkbook();   
  2.     HSSFSheet sheet = wb.createSheet("format sheet");   
  3.     HSSFFooter footer = sheet.getFooter();   
  4.   
  5.     footer.setRight( "Page " + HSSFFooter.page() + " of " + HSSFFooter.numPages() );   
  6.   
  7.   
  8.   
  9.     // Create various cells and rows for spreadsheet.   
  10.   
  11.     FileOutputStream fileOut = new FileOutputStream("workbook.xls");   
  12.     wb.write(fileOut);   
  13.     fileOut.close();  
HSSFWorkbook wb = new HSSFWorkbook();
    HSSFSheet sheet = wb.createSheet("format sheet");
    HSSFFooter footer = sheet.getFooter();

    footer.setRight( "Page " + HSSFFooter.page() + " of " + HSSFFooter.numPages() );



    // Create various cells and rows for spreadsheet.

    FileOutputStream fileOut = new FileOutputStream("workbook.xls");
    wb.write(fileOut);
    fileOut.close();

 

  备注:只有在打印预览的时候页脚才显示出来。

 20. 选中一个Sheet

Java代码 复制代码  收藏代码
  1. Workbook wb = new HSSFWorkbook();   
  2.   Sheet sheet = wb.createSheet("row sheet");   
  3.   sheet.setSelected(true);  
  Workbook wb = new HSSFWorkbook();
    Sheet sheet = wb.createSheet("row sheet");
    sheet.setSelected(true);

 

 21. 设置方法倍率

Java代码 复制代码  收藏代码
  1. Workbook wb = new HSSFWorkbook();   
  2.    Sheet sheet1 = wb.createSheet("new sheet");   
  3.    sheet1.setZoom(3,4);   // 75 percent magnification  
 Workbook wb = new HSSFWorkbook();
    Sheet sheet1 = wb.createSheet("new sheet");
    sheet1.setZoom(3,4);   // 75 percent magnification

 Zoom是一个分数,例如如果方法75%,那么分子为3,分母为4。

 

  22. 设置打印时的页宽和页高

 

Java代码 复制代码  收藏代码
  1. Workbook wb = new HSSFWorkbook();   
  2.     Sheet sheet = wb.createSheet("format sheet");   
  3.     PrintSetup ps = sheet.getPrintSetup();   
  4.   
  5.     sheet.setAutobreaks(true);   
  6.   
  7.     ps.setFitHeight((short)1);   
  8.     ps.setFitWidth((short)1);   
  9.   
  10.   
  11.     // Create various cells and rows for spreadsheet.   
  12.   
  13.     FileOutputStream fileOut = new FileOutputStream("workbook.xls");   
  14.     wb.write(fileOut);   
  15.     fileOut.close();  
Workbook wb = new HSSFWorkbook();
    Sheet sheet = wb.createSheet("format sheet");
    PrintSetup ps = sheet.getPrintSetup();

    sheet.setAutobreaks(true);

    ps.setFitHeight((short)1);
    ps.setFitWidth((short)1);


    // Create various cells and rows for spreadsheet.

    FileOutputStream fileOut = new FileOutputStream("workbook.xls");
    wb.write(fileOut);
    fileOut.close();

 

23. 移动行

 

Java代码 复制代码  收藏代码
  1. public void shiftRow() throws Exception{   
  2.         Workbook wb = new HSSFWorkbook();   
  3.         Sheet sheet = wb.createSheet("row sheet");   
  4.   
  5.         for(int i=0;i<20;i++){   
  6.             Row row=sheet.createRow(i);   
  7.             Cell cell=row.createCell(0);   
  8.             cell.setCellValue(""+i);   
  9.         }   
  10.         // Shift rows 6 - 11 on the spreadsheet to the top (rows 0 - 5)   
  11.         //把第6-11行向上移动5行   
  12.         sheet.shiftRows(510,-5);   
  13.         FileOutputStream fileOut = new FileOutputStream("workbook.xls");   
  14.         wb.write(fileOut);   
  15.         fileOut.close();   
  16.     }  
public void shiftRow() throws Exception{
		Workbook wb = new HSSFWorkbook();
        Sheet sheet = wb.createSheet("row sheet");

        for(int i=0;i<20;i++){
        	Row row=sheet.createRow(i);
        	Cell cell=row.createCell(0);
        	cell.setCellValue(""+i);
        }
        // Shift rows 6 - 11 on the spreadsheet to the top (rows 0 - 5)
        //把第6-11行向上移动5行
        sheet.shiftRows(5, 10,-5);
        FileOutputStream fileOut = new FileOutputStream("workbook.xls");
	    wb.write(fileOut);
	    fileOut.close();
	}

 POI学习笔记四将会介绍poi更高级的一些知识点。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值