Apache POI学习和使用

软件简介

Apache POI是基于Office Open XML标准(OOXML)和Microsoft的OLE 2复合文档格式(OLE2)处理各种文件格式的开源项目。 简而言之,您可以使用Java读写MS Excel文件,可以使用Java读写MS Word和MS PowerPoint文件。

模块

  • HSSF - 提供读写Microsoft Excel XLS格式(Microsoft Excel 97 (-2003))档案的功能。
  • XSSF - 提供读写Microsoft Excel OOXML XLSX格式(Microsoft Excel XML (2007+))档案的功能。
  • SXSSF - 提供低内存占用量读写Microsoft Excel OOXML XLSX格式档案的功能。
  • HWPF - 提供读写Microsoft Word DOC97格式(Microsoft Word 97 (-2003))档案的功能。
  • XWPF - 提供读写Microsoft Word DOC2003格式(WordprocessingML (2007+))档案的功能。
  • HSLF/XSLF - 提供读写Microsoft PowerPoint格式档案的功能。
  • HDGF/XDGF - 提供读Microsoft Visio格式档案的功能。
  • HPBF - 提供读Microsoft Publisher格式档案的功能。
  • HSMF - 提供读Microsoft Outlook格式档案的功能。

Maven依赖

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>4.1.2</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>4.1.2</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml-schemas</artifactId>
    <version>4.1.2</version>
</dependency>

官方文档

http://poi.apache.org/

正如前面所说,Apache POI 针对读写Excel 文件提供了三个组件:

HSSFXSSFSXSSF
HSSF是POI项目对Excel '97(-2007)文件格式的纯Java实现XSSF是POI项目对Excel 2007 OOXML(.xlsx)文件格式的纯Java实现。SXSSF是XSSF的API兼容流扩展,可用于必须生成非常大的电子表格且堆空间有限的情况
处理*.xls 文件处理*.xlsx 文件处理超大的*xlsx 文件
  • 3.8-beta3开始,POI提供了基于XSSF的低内存占用的SXSSF API。
  • SXSSF是XSSF的API兼容流扩展,可用于必须生成非常大的电子表格且堆空间有限的情况。SXSSF通过限制对滑动窗口内的行的访问来实现其低内存占用,而XSSF允许对文档中的所有行进行访问。不再存在于窗口中的较旧的行由于被写入磁盘而变得不可访问.
  • 在自动刷新模式下,可以指定访问窗口的大小,以在内存中保留一定数量的行。当达到该值时,创建额外的一行会导致索引最低的行从访问窗口中删除并写入磁盘。或者,可以将窗口大小设置为动态增长。可以根据需要通过显式调用flushRows(int keepRows)定期对其进行修剪。
  • 由于实现的流性质,与XSSF相比存在以下限制
    • 在某个时间点只能访问有限数量的行。
    • 不支持Sheet.clone()
    • 不支持公式评估

EXCEL封装常用代码块

1.1 常用代码块

1.1.1 标题样式 通常设置样式

public CellStyle getColumnStyle(SXSSFWorkbook workbook, int fontSize) {
    // 设置字体
    Font font = workbook.createFont();
    // 设置字体大小
    font.setFontHeightInPoints((short) fontSize);
    // 字体加粗
    font.setBoldweight(Font.BOLDWEIGHT_BOLD);
    // 设置字体名字
    font.setFontName("宋体");
    // 设置样式;
    CellStyle style = workbook.createCellStyle();
    // 设置底边框;
    style.setBorderBottom(CellStyle.BORDER_THIN);
    // 设置底边框颜色;
    style.setBottomBorderColor(HSSFColor.BLACK.index);
    // 设置左边框;
    style.setBorderLeft(CellStyle.BORDER_THIN);
    // 设置左边框颜色;
    style.setLeftBorderColor(HSSFColor.BLACK.index);
    // 设置右边框;
    style.setBorderRight(CellStyle.BORDER_THIN);
    // 设置右边框颜色;
    style.setRightBorderColor(HSSFColor.BLACK.index);
    // 设置顶边框;
    style.setBorderTop(CellStyle.BORDER_THIN);
    // 设置顶边框颜色;
    style.setTopBorderColor(HSSFColor.BLACK.index);
    // 在样式用应用设置的字体;
    style.setFont(font);
    // 设置自动换行;
    style.setWrapText(false);
    // 设置水平对齐的样式为居中对齐;
    style.setAlignment(CellStyle.ALIGN_CENTER);
    // 设置垂直对齐的样式为居中对齐;
    style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);

    // 设置背景填充色(前景色)
    style.setFillForegroundColor(HSSFColor.LIGHT_CORNFLOWER_BLUE.index);// 设置别的颜色请去网上查询相关文档
    style.setFillPattern(CellStyle.SOLID_FOREGROUND);
    return style;
}

1.1.2 内容通常设置样式

public CellStyle getStyle(SXSSFWorkbook workbook, int fontSize) {
    // 设置字体
    Font font = workbook.createFont();
    // 设置字体大小
    font.setFontHeightInPoints((short) fontSize);
    // 字体加粗
    // font.setBoldweight(Font.BOLDWEIGHT_BOLD);
    // 设置字体名字
    font.setFontName("宋体");
    // 设置样式;
    CellStyle style = workbook.createCellStyle();
    // 设置底边框;
    style.setBorderBottom(CellStyle.BORDER_THIN);
    // 设置底边框颜色;
    style.setBottomBorderColor(HSSFColor.BLACK.index);
    // 设置左边框;
    style.setBorderLeft(CellStyle.BORDER_THIN);
    // 设置左边框颜色;
    style.setLeftBorderColor(HSSFColor.BLACK.index);
    // 设置右边框;
    style.setBorderRight(CellStyle.BORDER_THIN);
    // 设置右边框颜色;
    style.setRightBorderColor(HSSFColor.BLACK.index);
    // 设置顶边框;
    style.setBorderTop(CellStyle.BORDER_THIN);
    // 设置顶边框颜色;
    style.setTopBorderColor(HSSFColor.BLACK.index);
    // 在样式用应用设置的字体;
    style.setFont(font);
    // 设置自动换行;
    style.setWrapText(false);
    // 设置水平对齐的样式为居中对齐;
    style.setAlignment(CellStyle.ALIGN_CENTER);
    // 设置垂直对齐的样式为居中对齐;
    style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);

    return style;
}

1.1.3 下载导出excel代码片段

SXSSFWorkbook workbook = new SXSSFWorkbook();
// 输出到用户浏览器上
try (OutputStream out = response.getOutputStream()) {
	// excel 表文件名
	String fileName = title + DateFormatUtils.format(new Date(), Constant.DATETIMEFORMAT_SHORT) + ".xlsx";
    String fileName11 = "";
    String userAgent = request.getHeader("USER-AGENT");
    if (!StringUtils.isEmpty(userAgent)) {
		if (userAgent.contains("Firefox") || userAgent.contains("firefox")) {// 火狐浏览器
			fileName11 = new String(fileName.getBytes(), "ISO8859-1");
		} else {
			fileName11 = URLEncoder.encode(fileName, "UTF-8");// 其他浏览器
		}
	}
    String headStr = "attachment; filename=\"" + fileName11 + "\"";
    response.setContentType("APPLICATION/OCTET-STREAM");
    response.setCharacterEncoding("UTF-8");
    response.setHeader("Content-Disposition", headStr);
    workbook.write(out);
    out.flush();
    workbook.close();
    workbook.dispose();
} catch (Exception e) {
	throw e;
}

1.1.4 excel导入

第一种:非2007版本导入

public static List<List<Object>> readExcel(File file) throws IOException, EncryptedDocumentException, InvalidFormatException {
	List<List<Object>> list = new LinkedList<List<Object>>();
	try (FileInputStream in = new FileInputStream(file); Workbook hwb = WorkbookFactory.create(in);) {
		Sheet sheet = hwb.getSheetAt(0);
		Object value = null;
		Row row = null;
		Cell cell = null;
		for (int i = sheet.getFirstRowNum(); i <= sheet.getPhysicalNumberOfRows(); i++) {
			row = sheet.getRow(i);
			if (row == null) {
				continue;
			}
			List<Object> linked = new LinkedList<Object>();
			for (int j = row.getFirstCellNum(); j <= row.getLastCellNum(); j++) {
				cell = row.getCell(j);
				if (cell == null) {
					continue;
				}
				// DecimalFormat df = new DecimalFormat("0");// 格式化 number
				// String 字符
				SimpleDateFormat sdf = new SimpleDateFormat(Constant.DATETIMEFORMAT);// 格式化日期字符串
				DecimalFormat nf = new DecimalFormat("0");// 格式化数字
				switch (cell.getCellType()) {
				case XSSFCell.CELL_TYPE_STRING:
					// System.out.println(i+"行"+j+" 列 is String type");
					value = cell.getStringCellValue();
					break;
				case XSSFCell.CELL_TYPE_NUMERIC:
					// System.out.println(i+"行"+j+" 列 is Number type ;
					// DateFormt:"+cell.getCellStyle().getDataFormatString());
					cell.setCellType(Cell.CELL_TYPE_NUMERIC);
					if ("@".equals(cell.getCellStyle().getDataFormatString())) {
						value = String.valueOf(cell.getNumericCellValue());
						if (((String) value).endsWith(".0")) {
							value = nf.format(cell.getNumericCellValue());
						}
					} else if ("General".equals(cell.getCellStyle().getDataFormatString())) {
						value = String.valueOf(cell.getNumericCellValue());
						if (((String) value).endsWith(".0")) {
							value = nf.format(cell.getNumericCellValue());
						}
					} else {
						value = sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue()));
					}
					break;
				case XSSFCell.CELL_TYPE_BOOLEAN:
					// System.out.println(i+"行"+j+" 列 is Boolean type");
					value = cell.getBooleanCellValue();
					break;
				case XSSFCell.CELL_TYPE_BLANK:
					// System.out.println(i+"行"+j+" 列 is Blank type");
					value = "";
					break;
				default:
					// System.out.println(i+"行"+j+" 列 is default type");
					value = cell.toString();
				}
				/*
				 * if (value == null || "".equals(value)) { continue; }
				 */
				linked.add(value);
			}
			list.add(linked);
		}
	} catch (Exception e) {
		throw e;

	}
	return list;
}

1.2 合并单元格

sheet.addMergedRegion(new CellRangeAddress(rowStart,rowEnd, columnStart, columnEnd))

1.3 数据有效性校验

  • 255个字符以内的直接设置内容即可
  • 超过255个字符,则需要 先将序列写入excel,然后当前单元格 引用序列位置

第一种:SXSSFSheet 内容小于255个字符,直接将list设置到单元格范围生效

// 设置下拉框属性
String[] list =  new String[] { "add,modify,delete" };
// 设置 数据校验helper
DataValidationHelper helper = sheet.getDataValidationHelper();
// 选择 数据校验应用到的单元格范围 
CellRangeAddressList addressList = new CellRangeAddressList(rowStart,rowEnd, columnStart, columnEnd);
// 设置下拉选项数据
DataValidationConstraint constraint = helper.createExplicitListConstraint(list);
// 生成单元格范围内校验的对象
DataValidation dataValidation = helper.createValidation(constraint, addressList);
// 开启 输入值校验,不存在则提示
dataValidation.setShowErrorBox(true);
// 设置进去
sheet.addValidationData(dataValidation);

第二种:SXSSFSheet 内容大于255个字符,使用引用其他位置作为数据校验对象

// 设置一行数据
SXSSFRow rowFieldName = sheetdic.createRow(i);
// 循环将校验的下拉数据写入到指定行内容
for (int j = 0; j < source.length; j++) {
	SXSSFCell cell = rowFieldName.createCell(j, SXSSFCell.CELL_TYPE_STRING);
	cell.setCellValue(source[j]);
}
// 获取下拉内容的单元格范围 'DIC'!$A$1:$A$3 
String strFormula = getCellName(i, source.length);
// 通过单元格范围生成 数据校验下拉列表对象
XSSFDataValidationConstraint constraint = new XSSFDataValidationConstraint(DataValidationConstraint.ValidationType.LIST, strFormula);
// 设置数据有效性加载在哪个单元格上,四个参数分别是:起始行、终止行、起始列、终止列
CellRangeAddressList addressList = new CellRangeAddressList(rowStart,rowEnd, columnStart, columnEnd);
// 数据有效性对象
DataValidationHelper helper = sheet.getDataValidationHelper();
DataValidation validation = helper.createValidation(constraint, addressList);
validation.setShowErrorBox(true);
sheet.addValidationData(validation);
// 将新建的sheet页隐藏掉
workbook.setSheetHidden(workbook.getSheetIndex(sheetdic), true);
					
					
/**
	* 获取校验序列范围
	* @param 第几行
	* @param 有多少个序列
	* @return 具体sheet的开启单元格和结束单元格
	* @author: os-lusd 2021年2月22日
	*/
private String getCellName(int i, Integer size) {
    String hex = column_to_name(size);
    // "'DIC'!$A$1:$A$3"
    return "'DIC'!$A$" + (i + 1) + ":$" + hex + "$" + (i + 1);
}

/**
	* 将十进制转换为excel的26进制字符串
	* @param n 十进制数字
	* @return 26进制符合excel的单元格位置
	* @author: os-lusd 2021年2月22日
	*/
private String column_to_name(Integer n) {
    String s = "";
    while (n > 0) {
        int m = n % 26;
        s = (char) (m - 1 + 'a') + s;
        n = (n - m) / 26;
    }
    return s;
}

POI API教程

1.4.1.1 如何创建一个WorkBook?

创建一个*.xls 文件

Workbook wb = new HSSFWorkbook();

创建一个*.xlsx 文件

Workbook wb = new XSSFWorkbook();

1.4.1.2 如何创建一个Sheet?

// sheetName 必须满足 最多31个字符,不能包含 // 0x0000|0x0003 // colon (:\*?/[])
Sheet sheet1 = wb.createSheet("new sheet");
// 可以使用POI提供方法 净化名称,不允许字符被替换为一个空格 “ ”
String safeName = WorkbookUtil.createSafeSheetName("[O'Brien's sales*?]"); 
// returns " O'Brien's sales   "

1.4.1.3 如何创建一个单元格?

// 创建行对象,角标从0开始
Row row = sheet.createRow(0);
// 创建该行的单元格对象,角标从0开始
Cell cell = row.createCell(0);
// 设置单元格值
cell.setCellValue(1);
// 获取单元格注释对象
CreationHelper createHelper = wb.getCreationHelper();
// 设置注释文本 “This is a string”
row.createCell(2).setCellValue(createHelper.createRichTextString("This is a string"));

1.4.1.4 如何创建一个日期类型的单元格?

// 获取管理对象
CreationHelper createHelper = wb.getCreationHelper();
// 创建 单元格样式
CellStyle cellStyle = wb.createCellStyle();
// 设置 日期格式化格式
cellStyle.setDataFormat(
    createHelper.createDataFormat().getFormat("m/d/yy h:mm"));
cell = row.createCell(1);
cell.setCellValue(new Date());
cell.setCellStyle(cellStyle);

1.4.1.5 创建多种格式的单元格

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(CellType.ERROR);

1.4.1.6 Files 和InputStream

当打开 WorkBook(.xls HSSFWorkbook或.xlsx XSSFWorkbook)时,可以从File 或InputStream加载工作簿。

  • 使用File对象可以减少内存消耗,

  • InputStream需要更多内存,因为它必须缓冲整个文件。

如果使用WorkbookFactory,则使用其中一个非常容易:

// 方式一 File
Workbook wb = WorkbookFactory.create(new File("MyExcel.xls"));
// 方式二 InputStream 需要更多的内存占用,
Workbook wb = WorkbookFactory.create(new FileInputStream("MyExcel.xlsx"));

如果直接使用HSSFWorkbook或XSSFWorkbook,通常应遍历POIFSFileSystem或 OPCPackage,以完全控制生命周期(包括完成后关闭文件):

// HSSFWorkbook, File
POIFSFileSystem fs = new POIFSFileSystem(new File("file.xls"));
HSSFWorkbook wb = new HSSFWorkbook(fs.getRoot(), true);
....
fs.close();
// HSSFWorkbook, InputStream, needs more memory
POIFSFileSystem fs = new POIFSFileSystem(myInputStream);
HSSFWorkbook wb = new HSSFWorkbook(fs.getRoot(), true);
// XSSFWorkbook, File
OPCPackage pkg = OPCPackage.open(new File("file.xlsx"));
XSSFWorkbook wb = new XSSFWorkbook(pkg);
....
pkg.close();
// XSSFWorkbook, InputStream, needs more memory
OPCPackage pkg = OPCPackage.open(myInputStream);
XSSFWorkbook wb = new XSSFWorkbook(pkg);
....
pkg.close();

1.4.1.7 展示各种对齐方式

  • 水平设置 HorizontalAlignment
    • CENTER
    • CENTER_SELECTION
    • FILL
    • GENERAL
    • JUSTIFY
    • LEFT
    • RIGHT
  • 垂直设置 VerticalAlignment
    • BOTTOM
    • CENTER
    • JUSTIFY
    • TOP
CellStyle cellStyle = wb.createCellStyle();
cellStyle.setAlignment(HorizontalAlignment.CENTER); //水平对其方式设置
cellStyle.setVerticalAlignment(valign); // 垂直对其方式
cell.setCellStyle(cellStyle);

1.4.1.8 设置边框

// Style the cell with borders all around.
CellStyle style = wb.createCellStyle();
style.setBorderBottom(BorderStyle.THIN);
style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
style.setBorderLeft(BorderStyle.THIN);
style.setLeftBorderColor(IndexedColors.GREEN.getIndex());
style.setBorderRight(BorderStyle.THIN);
style.setRightBorderColor(IndexedColors.BLUE.getIndex());
style.setBorderTop(BorderStyle.MEDIUM_DASHED);
style.setTopBorderColor(IndexedColors.BLACK.getIndex());
cell.setCellStyle(style);

1.4.1.9 遍历行和单元格

有时,可能只想遍历工作簿中的所有工作表中的所有行或行中的所有单元格。这可以通过简单的for循环来实现。

通过调用workbook.sheetIterator(), sheet.rowIterator()和row.cellIterator() 或隐式使用for-each循环,可以使用这些迭代器。请注意,rowIterator和cellIterator遍历已创建的行或单元格,跳过空的行和单元格。

for (Sheet sheet : wb ) {
    for (Row row : sheet) {
        for (Cell cell : row) {
            // Do something here
        }
    }
}

1.4.1.10 遍历单元格,控制丢失/空白的单元格

在某些情况下,进行迭代时,您需要完全控制如何处理丢失或空白的行和单元格,并且需要确保访问每个单元格,而不仅仅是访问文件中定义的那些单元格。(CellIterator将仅返回文件中定义的单元格,这在很大程度上是具有值或样式的单元格,但取决于Excel)。

在这种情况下,应获取一行的第一列和最后一列信息,然后调用getCell(int,MissingCellPolicy) 来获取单元格。使用 MissingCellPolicy 控制空白或空单元格的处理方式。

// Decide which rows to process
int rowStart = Math.min(15, sheet.getFirstRowNum());
int rowEnd = Math.max(1400, sheet.getLastRowNum());
for (int rowNum = rowStart; rowNum < rowEnd; rowNum++) {
   Row r = sheet.getRow(rowNum);
   if (r == null) {
      // This whole row is empty
      // Handle it as needed
      continue;
   }
   int lastColumn = Math.max(r.getLastCellNum(), MY_MINIMUM_COLUMN_COUNT);
   for (int cn = 0; cn < lastColumn; cn++) {
      Cell c = r.getCell(cn, Row.RETURN_BLANK_AS_NULL);
      if (c == null) {
         // The spreadsheet is empty in this cell
      } else {
         // Do something useful with the cell's contents
      }
   }
}

1.4.1.11 获取单元格内容

要获取单元格的内容,您首先需要知道它是哪种单元格(例如,将字符串单元格作为其数字内容将获得NumberFormatException)。因此,您将需要打开单元格的类型,然后为该单元格调用适当的getter。

在下面的代码中,我们遍历一张纸中的每个单元格,打印出该单元格的引用(例如A3),然后打印出该单元格的内容。

// import org.apache.poi.ss.usermodel.*;
DataFormatter formatter = new DataFormatter();
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(" - ");
        // get the text that appears in the cell by getting the cell value and applying any data formats (Date, 0.00, 1.23e9, $1.23, etc)
        String text = formatter.formatCellValue(cell);
        System.out.println(text);
        // Alternatively, get the value and format it yourself
        switch (cell.getCellType()) {
            case CellType.STRING:  // 字符串
                System.out.println(cell.getRichStringCellValue().getString());
                break;
            case CellType.NUMERIC:  // 数字
                if (DateUtil.isCellDateFormatted(cell)) {
                    System.out.println(cell.getDateCellValue());
                } else {
                    System.out.println(cell.getNumericCellValue());
                }
                break;
            case CellType.BOOLEAN:  // 布尔值
                System.out.println(cell.getBooleanCellValue());
                break;
            case CellType.FORMULA:  // 
                System.out.println(cell.getCellFormula());
                break;
            case CellType.BLANK:   // 空白
                System.out.println();
                break;
            default:
                System.out.println();
        }
    }
}

1.4.1.11 文字提取

对于大多数文本提取要求,标准ExcelExtractor类应提供您所需要的全部。

try (InputStream inp = new FileInputStream("workbook.xls")) {
    HSSFWorkbook wb = new HSSFWorkbook(new POIFSFileSystem(inp));
    ExcelExtractor extractor = new ExcelExtractor(wb);
    extractor.setFormulasNotResults(true);
    extractor.setIncludeSheetNames(false);
    String text = extractor.getText();
    wb.close();
}

对于非常精美的文本提取,XLS到CSV等,请查看 /src/examples/src/org/apache/poi/examples/hssf/eventusermodel/XLS2CSVmra.java

1.4.1.12 填充和颜色

// Aqua background
CellStyle style = wb.createCellStyle();
style.setFillBackgroundColor(IndexedColors.AQUA.getIndex());  //
style.setFillPattern(FillPatternType.BIG_SPOTS);
cell.setCellStyle(style);

1.4.1.13 合并单元格

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

1.4.1.14 设置字体

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);
cell.setCellStyle(style);

请注意,工作簿中唯一字体的最大数量限制为32767。您应该在应用程序中重新使用字体,而不是为每个单元格创建字体。

1.4.1.15 自定义颜色

HSSF(*.xls文件)

HSSFCellStyle style = wb.createCellStyle();
style.setFillForegroundColor(HSSFColor.LIME.index);
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
HSSFFont font = wb.createFont();
font.setColor(HSSFColor.RED.index);
style.setFont(font);
cell.setCellStyle(style);

XSSF(*.xlsx 文件)

cell.setCellValue("custom XSSF colors");
XSSFCellStyle style1 = wb.createCellStyle();
style1.setFillForegroundColor(new XSSFColor(new java.awt.Color(128, 0, 128), new DefaultIndexedColorMap()));
style1.setFillPattern(FillPatternType.SOLID_FOREGROUND);

1.4.1.16 读和写WorksBooks

try (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(CellType.STRING);
    cell.setCellValue("a test");
    // Write the output to a file
    try (OutputStream fileOut = new FileOutputStream("workbook.xls")) {
        wb.write(fileOut);
    }
}

1.4.1.17 在单元格中使用换行符

  • CellStyle 必须设置setWrapText(true) 才可生效
cell.setCellValue("Use \n with word wrap on to create a new line");
CellStyle cs = wb.createCellStyle();
cs.setWrapText(true); // 如果 换行符生效,wrap=true 才可性
cell.setCellStyle(cs);
//设置行高
row.setHeightInPoints((2*sheet.getDefaultRowHeightInPoints()));
// 设置默认字体大小
sheet.autoSizeColumn(2);

1.4.1.18 数据格式化

DataFormat format = wb.createDataFormat();
cell = row.createCell(colNum);
cell.setCellValue(11111.25);
style = wb.createCellStyle();
style.setDataFormat(format.getFormat("#,##0.0000"));
cell.setCellStyle(style);

1.4.1.19 将工作表调整为一页

PrintSetup ps = sheet.getPrintSetup();
sheet.setAutobreaks(true);
ps.setFitHeight((short)1);
ps.setFitWidth((short)1);

1.4.1.20 设置打印区域

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
);

1.4.1.21 设置页脚页数

Footer footer = sheet.getFooter();
footer.setRight( "Page " + HeaderFooter.page() + " of " + HeaderFooter.numPages() );
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值