gpt4 book ai didi

java - 如何增强这个使用 POI 和 JXL 读取 xls 文件的 java 类?

转载 作者:行者123 更新时间:2023-11-29 09:05:15 24 4
gpt4 key购买 nike

我目前正在使用 POI 读取 excel 文件并且它工作得很好,除了它无法读取旧格式的 xls 文件(BIFF5/office 95)来解决这个问题我正在捕获 OldExcelFormatException 并且在这种情况下调用一个函数将使用 jxl 读取 xls 文件。我想要实现的是编写相同的代码但不捕获异常。这是当前的工作代码:

public void translate() throws IOException, CmpException
{
ArrayList<String> row = null;

try
{
// create a new org.apache.poi.poifs.filesystem.Filesystem
POIFSFileSystem poifs = new POIFSFileSystem(fin);
w = new HSSFWorkbook(poifs);
}
catch (OldExcelFormatException e) // OldExcelFormatException
{
w = null;
System.out.println("OldExcelFormatException");
translateBIFF5();
}
catch (Exception e) // Any Exception
{
w = null;
}

if (w != null)
{
// read the excel file using POI
}
}

private void translateBIFF5() throws IOException, CmpException
{
ArrayList<String> row = null;
try
{
jxl_w = Workbook.getWorkbook(excelFile);
}
catch (Exception e) // Any Exception
{
jxl_w = null;
}

if (jxl_w != null)
{
// read the excel file using jxl
}
}

最佳答案

别介意伙计们。我自己找到了解决方案。诀窍是查看工作簿名称:对于 excel 95/97,工作簿名称为“Book”,而对于新格式,工作簿名称为“WorkBook”。所以这是我一直在寻找的一段代码:

  POIFSFileSystem poifs = new POIFSFileSystem(fin);

DirectoryNode directory = poifs.getRoot();
Iterator<Entry> i = directory.getEntries();
while (i.hasNext())
{
Entry e = i.next();
String bookName = e.getName();
if (bookName.equals("Book"))
{
System.out.println("This is an old format");
}
else
{
System.out.println("This is a new format");
}
}

关于java - 如何增强这个使用 POI 和 JXL 读取 xls 文件的 java 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15385009/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com