提问人:justcurious 提问时间:10/25/2023 最后编辑:justcurious 更新时间:10/26/2023 访问量:75
将 .xls 文件转换为 .xlsx 文件
Converting .xls file to .xlsx file
问:
我有一个 .xls 格式的 Excel 文件,我想将其转换为或另存为具有相同内容的 .xlsx 文件。
我尝试了以下方法
package Test;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class xlstoxlsx {
public static void convert(String xlsFilePath, String xlsxFilePath) throws IOException {
FileInputStream xlsFile = new FileInputStream(xlsFilePath);
HSSFWorkbook xlswb = new HSSFWorkbook(xlsFile);
XSSFWorkbook xlsxwb = new XSSFWorkbook();
for (int i = 0; i < xlswb.getNumberOfSheets(); i++) {
xlsxwb.createSheet(xlswb.getSheetName(i));
}
FileOutputStream xlsxFile = new FileOutputStream(xlsxFilePath);
xlswb.write(xlsxFile);
xlswb.close();
xlsxwb.close();
xlsFile.close();
xlsxFile.close();
}
public static void main (String args[]) throws IOException {
xlstoxlsx.convert("C:\\Users\\user\\Desktop\\Test1.xls", "C:\\Users\\user\\Desktop\\Test2.xlsx");
}
}
Exception in thread "main" org.apache.poi.poifs.filesystem.OfficeXmlFileException: The supplied data appears to be in the Office 2007+ XML. You are calling the part of POI that deals with OLE2 Office Documents. You need to call a different part of POI to process this data (eg XSSF instead of HSSF)
at org.apache.poi.poifs.storage.HeaderBlock.<init>(HeaderBlock.java:130)
at org.apache.poi.poifs.storage.HeaderBlock.<init>(HeaderBlock.java:117)
at org.apache.poi.poifs.filesystem.POIFSFileSystem.<init>(POIFSFileSystem.java:285)
at org.apache.poi.hssf.usermodel.HSSFWorkbook.<init>(HSSFWorkbook.java:400)
at org.apache.poi.hssf.usermodel.HSSFWorkbook.<init>(HSSFWorkbook.java:381)
at Test.xlstoxlsx.convert(xlstoxlsx.java:15)
at Test.xlstoxlsx.main(xlstoxlsx.java:35)
我在这里做错了什么?有没有更好的方法可以将 .xls 转换为 .xlsx 格式?
答: 暂无答案
评论