POI操作Excel相关方法总结
POI相关介绍、下载以及API可以参照之前的博客:
以下是相关方法,POI版本为3.16:
1.测试导出Excel
简单测试模拟导出Excel过程,首先前两行合并单元格,并创建隶书字体、加粗,设置边框;对于列标题,设置宋体、加粗、边框等样式;对于数据,设置的都是字符串类型,实际过程中有可能是浮点型、日期等格式,这里只是简单模拟一下。
(1).创建单元格样式、设置边框、设置字体等
/**
* 创建单元格样式
* @param workbook 工作薄
* @param fontName 字体名称
* @param fontSize 字体大小
* @param bold 是否加粗
* @return HSSFCellStyle 单元格样式
* @date 2017年6月12日
* <p>Description:</p>
*/
public CellStyle createCellStyle(Workbook workbook, String fontName, short fontSize, boolean bold){
CellStyle cellStyle = workbook.createCellStyle();
// 居中
cellStyle.setAlignment(HorizontalAlignment.CENTER);// 水平居中
cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);// 垂直居中
// 边框
this.setBorder(cellStyle);
// 字体
cellStyle.setFont(this.createFont(workbook, fontName, fontSize, bold));
return cellStyle;
}
/**
* Description:设置单元格边框
* @param cellStyle 单元格样式
* @return 单元格样式
* @date 2017年6月12日
* <p>Description:</p>
*/
public CellStyle setBorder(CellStyle cellStyle) {
if (cellStyle != null) {
cellStyle.setBorderBottom(BorderStyle.THIN); // 下边框
cellStyle.setBorderLeft(BorderStyle.THIN); // 左下边框
cellStyle.setBorderRight(BorderStyle.THIN); // 右边框
cellStyle.setBorderTop(BorderStyle.THIN); // 上边框
}
return cellStyle;
}
/**
* Description:创建字体
* @param workbook 工作薄
* @param fontName 字体名称,默认宋体
* @param fontSize 字体大小
* @param bold 是否加粗
* @return 字体
* @date 2017年6月12日
* <p>Description:</p>
*/
public Font createFont(Workbook workbook, String fontName, short fontSize, boolean bold) {
Font font = workbook.createFont();
font.setFontName(fontName == null || fontName.trim() == "" ? "宋体" : fontName);// 字体名
font.setBold(bold);// 加粗
font.setFontHeightInPoints(fontSize);// 字体大小
return font;
}
(2).导出Excel
/**
* Description:导出Excel
* @param isO3Excel 是否是03Excel
* @param outputStream 输出流
* @param columnNames 列名
* @param values 值
* @date 2017年6月12日
* <p>Description:</p>
*/
public void testExportExcel(boolean isO3Excel, OutputStream outputStream, String columnNames[],
List<String[]> values) {
Workbook workbook = null;
try {
workbook = isO3Excel ? new HSSFWorkbook() : new XSSFWorkbook();
// 工作单
Sheet sheet = workbook.createSheet();
// 合并单元格
sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, columnNames.length - 1));
// 设置单元格默认宽度 高度
sheet.autoSizeColumn(0);
sheet.setDefaultRowHeightInPoints(16);
// 自定义单元格宽度
for (int i = 0; i < columnNames.length; i++)
sheet.setColumnWidth(i, 20 * 256);
// 头标题
CellStyle headCellStyle = this.createCellStyle(workbook, "隶书", (short) 18, true);
Row headRow = sheet.createRow(0);
Cell headCell = headRow.createCell(0);
headCell.setCellStyle(headCellStyle);
headCell.setCellValue("用户信息");
// 列标题
CellStyle coulumnNameStyle = this.createCellStyle(workbook, "宋体", (short) 14, true);
Row columnRow = sheet.createRow(2);
for (int i = 0; i < columnNames.length; i++) {
Cell columnCell = columnRow.createCell(i);
columnCell.setCellStyle(coulumnNameStyle);
columnCell.setCellValue(columnNames[i]);
}
// 数据
CellStyle cellStyle = this.createCellStyle(workbook, "宋体", (short) 11, false);
for (int i = 0; i < values.size(); i++) {
String[] rowValues = values.get(i);
if (rowValues != null) {
Row row = sheet.createRow(i + 3);
// 设置数据
for (int index = 0; index < rowValues.length; index++) {
Cell cell = row.createCell(index);
cell.setCellValue(rowValues[index]);
cell.setCellStyle(cellStyle);
}
}
}
workbook.write(outputStream);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (outputStream != null)
outputStream.close();
if (workbook != null)
workbook.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
(3).测试代码及结果
boolean isO3Excel = false;
OutputStream outputStream = new FileOutputStream("D:/poiTest/测试Excel.xlsx");
String columnNames[] = {"姓名", "性别", "手机"};
List<String[]> values = new ArrayList<String[]>();
values.add(new String[] { "张三", "男", "123456789" });
values.add(new String[] { "李四", "男", "123456789" });
values.add(new String[] { "王五", "男", "123456789" });
testExportExcel(isO3Excel, outputStream, columnNames, values);
2.测试读取Excel
测试读取Excel,通过is03Excel设置true、false可解析03或07及之后的Excel
(1).读取数据
/**
* Description:测试读取Excel
* @param isO3Excel 是否是03Excel
* @param inputStream 输入流
* @throws Exception
* @date 2017年6月11日
* <p>Description:</p>
*/
public List<String[]> testImportExcel(boolean isO3Excel, InputStream inputStream) throws Exception {
List<String[]> values = null;
Workbook workbook = null;
try {
workbook = isO3Excel ? new HSSFWorkbook(inputStream) : new XSSFWorkbook(inputStream);
Sheet sheet = workbook.getSheetAt(0);
if(sheet.getPhysicalNumberOfRows() > 3){
values = new ArrayList<String[]>();
for (int i = 3; i < sheet.getPhysicalNumberOfRows(); i++) {
Row row = sheet.getRow(i);
String name = POIUtils.parseToString(row.getCell(0));
String sex = POIUtils.parseToString(row.getCell(1));
String phone = POIUtils.parseToString(row.getCell(2));
values.add(new String[] { name, sex, phone });
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (inputStream != null)
inputStream.close();
if (workbook != null)
workbook.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return values;
}
(2).POIUtils.java
/**
* Description:将单元格数据转换成字符串
* @param cell 单元格
* @return cell为空返回null,否则返回值
* @date 2017年6月12日
* <p>Description:</p>
*/
public static String parseToString(Cell cell) {
return cell == null ? null : cell.getStringCellValue();
}
(3).测试代码及结果
boolean isO3Excel = false;
InputStream inputStream = new FileInputStream("D:/poiTest/测试Excel.xlsx");
List<String[]> values = testImportExcel(isO3Excel, inputStream);
if (values != null && values.size() > 0) {
Iterator<String[]> it = values.iterator();
while (it.hasNext()) {
String[] value = it.next();
System.out.println("姓名:" + value[0] + ",性别:" + value[1] + ",手机:" + value[2]);
}
}