我正在尝试使用 Apache POI 3.9 从字符串中读取 excel 文件,但没有成功。我对java不太熟悉。
澄清一下,在我的程序中,我已经将 excel 文件作为字符串,并且我正在使用 readFile 函数来模拟这种行为。
程序:
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
public class Test {
static String readFile(String path, Charset encoding) throws IOException
{
byte[] encoded = Files.readAllBytes(Paths.get(path));
return encoding.decode(ByteBuffer.wrap(encoded)).toString();
}
public static void main(String[] args) throws IOException, InvalidFormatException {
String result = readFile("data.xlsx", StandardCharsets.UTF_8);
InputStream is = new ByteArrayInputStream(result.getBytes("UTF-8"));
Workbook book = WorkbookFactory.create(is);
}
}
我得到的错误是:
Exception in thread "main" java.util.zip.ZipException: invalid block type
at java.util.zip.InflaterInputStream.read(InflaterInputStream.java:164)
at java.util.zip.ZipInputStream.read(ZipInputStream.java:193)
at java.io.FilterInputStream.read(FilterInputStream.java:107)
at org.apache.poi.openxml4j.util.ZipInputStreamZipEntrySource$FakeZipEntry.<init>(ZipInputStreamZipEntrySource.java:127)
at org.apache.poi.openxml4j.util.ZipInputStreamZipEntrySource.<init>(ZipInputStreamZipEntrySource.java:55)
at org.apache.poi.openxml4j.opc.ZipPackage.<init>(ZipPackage.java:83)
at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:267)
at org.apache.poi.ss.usermodel.WorkbookFactory.create(WorkbookFactory.java:73)
at Test.main(Test.java:28)
任何帮助,将不胜感激。
干杯