读取和写入一个Excel或者Word文件是一个很常见的需求,可以通过Apache提供的Workbook接口来操作。
Workbook有两个实现类:XSSFWorkbook和HSSFWorkbook,这两个实现类都能实现相关的功能;不同的是操作的Excel的版本不同。HSSFWorkbook生成的文件后缀名是.xls,而XSSFWorkbook生成的文件的后缀名是.xlsx。
两个版本的关系,能打开.xls的软件,不一定能打开.xlsx文件,而能打开.xlsx的文件的软件,一定能打开.xls文件。如果不确定系统的版本,我会在读取Excel文件的时候使用XSSFWorkbook。
Excel的写入 最基本的数据写入org.apache.poi poi 3.14 org.apache.poi poi-ooxml 3.14
public class ExcelUtil {
public static void createExcel(String path) throws Exception {
// 创建一个Excel对象
Workbook workbook = new XSSFWorkbook();
// 创建一个 sheet 表对象
Sheet sheet1 = workbook.createSheet("sheet1");
for (int i = 0; i < 10; i++) {
Row row = sheet1.createRow(i);
for (int j = 0; j < 10; j++) {
Cell cell = row.createCell(j);
cell.setCellValue("行"+(i+1)+",列"+(j+1));
}
}
File file = new File(path);
FileOutputStream fos = new FileOutputStream(file);
workbook.write(fos);
fos.close();
}
public static void main(String[] args) throws Exception {
createExcel("G:/myfile/office.xlsx");
}
}
标题以及标题样式的数据写入
public class ExcelUtil {
public static void createExcel(String path) throws Exception {
// 创建一个Excel对象
Workbook workbook = new XSSFWorkbook();
// 创建一个 sheet 表对象
Sheet sheet1 = workbook.createSheet("sheet1");
sheet1.addMergedRegion(new CellRangeAddress(0,0,0,9));
XSSFCellStyle cellStyle = (XSSFCellStyle) workbook.createCellStyle();
cellStyle.setAlignment(HorizontalAlignment.CENTER);
cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
XSSFFont font = (XSSFFont) workbook.createFont();
font.setBold(true);
cellStyle.setFont(font);
for (int i = 0; i < 10; i++) {
Row row = sheet1.createRow(i);
if (i == 0){
Cell cell = row.createCell(0);
cell.setCellValue("标题");
cell.setCellStyle(cellStyle);
continue;
}
for (int j = 0; j < 10; j++) {
Cell cell = row.createCell(j);
cell.setCellValue("行"+(i+1)+",列"+(j+1));
}
}
File file = new File(path);
FileOutputStream fos = new FileOutputStream(file);
workbook.write(fos);
fos.close();
}
public static void main(String[] args) throws Exception {
createExcel("G:/myfile/office.xlsx");
}
}



