ITeye博客

POI学习笔记(二)

canfly2010 · 2010-06-29 15:12 · java · 编程语言 · Markdown

7.  设置单元格的边框

 

Java代码 复制代码

  1. public void createBorder() throws Exception {
  2. Workbook wb = new HSSFWorkbook();
  3. Sheet sheet = wb.createSheet("new sheet");
  4. // Create a row and put some cells in it. Rows are 0 based.
  5. Row row = sheet.createRow(1);
  6. // Create a cell and put a value in it.
  7. Cell cell = row.createCell(1);
  8. cell.setCellValue(4);
  9. // Style the cell with borders all around.
  10. CellStyle style = wb.createCellStyle();
  11. style.setBorderBottom(CellStyle.BORDER_THIN);
  12. style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
  13. style.setBorderLeft(CellStyle.BORDER_THIN);
  14. style.setLeftBorderColor(IndexedColors.GREEN.getIndex());
  15. style.setBorderRight(CellStyle.BORDER_THIN);
  16. style.setRightBorderColor(IndexedColors.BLUE.getIndex());
  17. style.setBorderTop(CellStyle.BORDER_MEDIUM_DASHED);
  18. style.setTopBorderColor(IndexedColors.BLACK.getIndex());
  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();
  24. }
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. switch (cell.getCellType()) {
  12. case Cell.CELL_TYPE_STRING:
  13. System.out.println(cell.getRichStringCellValue()
  14. .getString());
  15. break;
  16. case Cell.CELL_TYPE_NUMERIC:
  17. if (DateUtil.isCellDateFormatted(cell)) {
  18. System.out.println(cell.getDateCellValue());
  19. } else {
  20. System.out.println(cell.getNumericCellValue());
  21. }
  22. break;
  23. case Cell.CELL_TYPE_BOOLEAN:
  24. System.out.println(cell.getBooleanCellValue());
  25. break;
  26. case Cell.CELL_TYPE_FORMULA:
  27. System.out.println(cell.getCellFormula());
  28. break;
  29. default:
  30. System.out.println();
  31. }
  32. }
  33. }
  34. }
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. ExcelExtractor extractor = new ExcelExtractor(wb);
  4. extractor.setFormulasNotResults(true);
  5. extractor.setIncludeSheetNames(true);
  6. String text = extractor.getText();
  7. 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. // Create a row and put some cells in it. Rows are 0 based.
  5. Row row = sheet.createRow((short) 1);
  6. // Aqua background
  7. CellStyle style = wb.createCellStyle();
  8. style.setFillBackgroundColor(IndexedColors.BLUE.getIndex());
  9. style.setFillPattern(CellStyle.ALIGN_FILL);
  10. Cell cell = row.createCell((short) 1);
  11. cell.setCellValue("X");
  12. cell.setCellStyle(style);
  13. // Orange "foreground", foreground being the fill foreground not the font color.
  14. style = wb.createCellStyle();
  15. style.setFillForegroundColor(IndexedColors.ORANGE.getIndex());
  16. style.setFillPattern(CellStyle.SOLID_FOREGROUND);
  17. cell = row.createCell((short) 2);
  18. cell.setCellValue("X");
  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();
  24. }
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((short) 1);
  5. Cell cell = row.createCell((short) 1);
  6. cell.setCellValue("This is a test of merging");
  7. sheet.addMergedRegion(new CellRangeAddress(1, // first row (0-based)
  8. 4, // last row (0-based)
  9. 1, // first column (0-based)
  10. 6 // last column (0-based)
  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 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. // Create a row and put some cells in it. Rows are 0 based.
  5. Row row = sheet.createRow(1);
  6. // Create a new font and alter it.
  7. Font font = wb.createFont();
  8. font.setFontHeightInPoints((short)24);
  9. font.setFontName("Courier New");
  10. font.setItalic(true);
  11. font.setStrikeout(true);
  12. // Fonts are set into a style so create a new one to use.
  13. CellStyle style = wb.createCellStyle();
  14. style.setFont(font);
  15. // Create a cell and put a value in it.
  16. Cell cell = row.createCell(1);
  17. cell.setCellValue("This is a test of fonts");
  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();
  23. }
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((short) 0);
  4. CellStyle style = workbook.createCellStyle();
  5. Font font = workbook.createFont();
  6. font.setBoldweight(Font.BOLDWEIGHT_BOLD);
  7. style.setFont(font);
  8. cell.setCellStyle(style);
  9. }
  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代码 复制代码

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

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。