如果使用的XSSFWorkbook创建的xls,打开的时候会有这样的提示:
这样 XSSFWorkbook 和HSSFWorkbook的区别。
HSSF - 提供读写Microsoft Excel XLS格式档案的功能。
XSSF - 提供读写Microsoft Excel OOXML XLSX格式档案的功能。
HWPF - 提供读写Microsoft Word DOC97格式档案的功能。
XWPF - 提供读写Microsoft Word DOC2003格式档案的功能。
HSLF - 提供读写Microsoft PowerPoint格式档案的功能。
HDGF - 提供读Microsoft Visio格式档案的功能。
HPBF - 提供读Microsoft Publisher格式档案的功能。
HSMF - 提供读Microsoft Outlook格式档案的功能。
使用POI创建一个新的xlsx,提示创建成功,但是打开xlsx文件的时候,会报错打不开
代码如下:
//定义表头
String[] title={“序号”,“姓名”,“年龄”};
//创建excel工作簿
HSSFWorkbook workbook=new HSSFWorkbook();
//创建工作表sheet
HSSFSheet sheet=workbook.createSheet(“first sheet”);
//创建第一行
HSSFRow row=sheet.createRow(0);
HSSFCell cell=null;
//插入第一行数据的表头
for(int i=0;i<title.length;i++){
cell=row.createCell(i);
cell.setCellValue(title[i]);
}
//写入数据
for (int i=1;i<=10;i++){
HSSFRow nrow=sheet.createRow(i);
HSSFCell ncell=nrow.createCell(0);
ncell.setCellValue(""+i);
ncell=nrow.createCell(1);
ncell.setCellValue(“user”+i);
ncell=nrow.createCell(2);
ncell.setCellValue(“24”);
}
//创建excel文件
File file=new File(“h://poi.xlsx”);
try {
file.createNewFile();
//将excel写入
FileOutputStream stream= FileUtils.openOutputStream(file);
workbook.write(stream);
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
报错是因为,HSSFWorkbook 改成XSSFWorkbook ,对应有“HSSF”全部去掉。另外会缺少以下jar包,导入即可:
commons-collections4-4.1.jar
xmlbeans-2.6.0.jar。
代码改良如下:
//定义表头
String[] title={“序号”,“姓名”,“年龄”};
//创建excel工作簿
XSSFWorkbook workbook=new XSSFWorkbook();
//创建工作表sheet
Sheet sheet=workbook.createSheet(“first sheet”);
//创建第一行
Row row=sheet.createRow(0);
Cell cell=null;
//插入第一行数据的表头
for(int i=0;i<title.length;i++){
cell=row.createCell(i);
cell.setCellValue(title[i]);
}
//写入数据
for (int i=1;i<=10;i++){
Row nrow=sheet.createRow(i);
Cell ncell=nrow.createCell(0);
ncell.setCellValue(""+i);
ncell=nrow.createCell(1);
ncell.setCellValue(“user”+i);
ncell=nrow.createCell(2);
ncell.setCellValue(“24”);
}
//创建excel文件
File file=new File(“h://poi.xlsx”);
try {
file.createNewFile();
//将excel写入
FileOutputStream stream= FileUtils.openOutputStream(file);
workbook.write(stream);
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
问题亲测已解决!!!!