我需要将xml电子表格2003转换为.xlsx格式。使用java代码将.xls转换为.xlsx格式
在我的应用程序中有一个链接,如果我点击该链接,它将在下载文件夹中下载该文件。当我尝试打开该excel文件时,它给出了一条消息
“文件格式和扩展名不匹配,文件可能损坏或不安全,除非您信任其源,请勿打开它。无论如何都想打开它?“
它给出选项是,否和帮助。
如果我点击是,那么我可以看到Excel表格内容。 Excel表扩展名为.xls,但是当我转到Excel表单中的文件并单击'另存为'时,它显示保存为类型是XML电子表格2003.
我可以手动保存为.xlsx,但是每次我都做不到。即使我试着用下面的代码
public class xls2xlsx {
public static void main(String[] args) throws InvalidFormatException,
IOException {
String inpFn = "F:\\Users\\Downloads\\Report.xls";
String outFn = "F:\\Users\\Downloads\\Report.xlsx";
InputStream in = new BufferedInputStream(new FileInputStream(inpFn));
try {
Workbook wbIn = new HSSFWorkbook(in);
File outF = new File(outFn);
if (outF.exists())
outF.delete();
Workbook wbOut = new XSSFWorkbook();
int sheetCnt = wbIn.getNumberOfSheets();
for (int i = 0; i < sheetCnt; i++) {
Sheet sIn = wbIn.getSheetAt(0);
Sheet sOut = wbOut.createSheet(sIn.getSheetName());
Iterator<Row> rowIt = sIn.rowIterator();
while (rowIt.hasNext()) {
Row rowIn = rowIt.next();
Row rowOut = sOut.createRow(rowIn.getRowNum());
Iterator<Cell> cellIt = rowIn.cellIterator();
while (cellIt.hasNext()) {
Cell cellIn = cellIt.next();
Cell cellOut = rowOut.createCell(
cellIn.getColumnIndex(), cellIn.getCellType());
switch (cellIn.getCellType()) {
case Cell.CELL_TYPE_BLANK:
break;
case Cell.CELL_TYPE_BOOLEAN:
cellOut.setCellValue(cellIn.getBooleanCellValue());
break;
case Cell.CELL_TYPE_ERROR:
cellOut.setCellValue(cellIn.getErrorCellValue());
break;
case Cell.CELL_TYPE_FORMULA:
cellOut.setCellFormula(cellIn.getCellFormula());
break;
case Cell.CELL_TYPE_NUMERIC:
cellOut.setCellValue(cellIn.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING:
cellOut.setCellValue(cellIn.getStringCellValue());
break;
}
{
CellStyle styleIn = cellIn.getCellStyle();
CellStyle styleOut = cellOut.getCellStyle();
styleOut.setDataFormat(styleIn.getDataFormat());
}
cellOut.setCellComment(cellIn.getCellComment());
// HSSFCellStyle cannot be cast to XSSFCellStyle
// cellOut.setCellStyle(cellIn.getCellStyle());
}
}
}
OutputStream out = new BufferedOutputStream(new FileOutputStream(
outF));
try {
wbOut.write(out);
} finally {
out.close();
}
} finally {
in.close();
}
}
}
错误
Exception in thread "main" java.io.IOException: Invalid header signature; read 0x6576206C6D783F3C, expected 0xE11AB1A1E011CFD0
at org.apache.poi.poifs.storage.HeaderBlock.<init>(HeaderBlock.java:140)
at org.apache.poi.poifs.storage.HeaderBlock.<init>(HeaderBlock.java:104)
at org.apache.poi.poifs.filesystem.POIFSFileSystem.<init>(POIFSFileSystem.java:138)
at org.apache.poi.hssf.usermodel.HSSFWorkbook.<init>(HSSFWorkbook.java:322)
at org.apache.poi.hssf.usermodel.HSSFWorkbook.<init>(HSSFWorkbook.java:303)
at excelSheet.xls2xlsx.main(xls2xlsx.java:42)
欢迎来到SO,请问一下问题:你有什么试过,你期望什么等等。问)。发布一些代码,你还有什么尝试 – Nehal
感谢Nehal,现在我清楚地解释了我的问题,请通过上述内容。 – Prasad
您尚未指定您的问题。你发布的代码有什么问题? –