问题描述
我想在excel文件的特定单元格上写入一些数据,但是我总是遇到相同的错误。 我使用Apache POI读写模板文件:
Exception in thread "Thread-4" org.apache.poi.openxml4j.exceptions.OpenXML4JRuntimeException: Fail to save: an error occurs while saving the package : class org.apache.poi.openxml4j.util.ZipSecureFile$ThresholdInputStream cannot be cast to class java.util.zip.ZipFile$ZipFileInputStream (org.apache.poi.openxml4j.util.ZipSecureFile$ThresholdInputStream is in unnamed module of loader 'app'; java.util.zip.ZipFile$ZipFileInputStream is in module java.base of loader 'bootstrap')
主要:
private final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
private final File pathTemplate = newFile(Objects.requireNonNull(classLoader.getResource("excel/template.xlsx")).toURI());
public void updaterapport(int indexSheet,int rowwnum,int cellnum,String value,File file) throws IOException,InvalidFormatException {
Workbook workbook = WorkbookFactory.create(new File(file.getPath()));
// Get Sheet
Sheet sheet = workbook.getSheetAt(indexSheet);
System.out.println(sheet.getSheetName());
// Get Row
Row row = sheet.getRow(rowwnum);
// Get the Cell
Cell cell = row.getCell(cellnum);
// Update the cell
cell.setCellType(CellType.STRING);
cell.setCellValue(value);
// Write the output to the file
try(FileOutputStream fileOut = new FileOutputStream(file.getName()))
{
workbook.write(fileOut);
}
// Closing the workbook
workbook.close();
}
public static void main(String[] args) {
updaterapport(0,1,2,"ok",pathTemplate);
}
解决方法
这是因为当您的资源位于jar文件中时,您无法将其视为文件。
如果需要文件,请将资源内容写入临时文件,然后使用它。
像这样:
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import org.junit.Test;
public class FirstTest {
@Test
public void resourceTest() throws IOException {
final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
final InputStream resource = classLoader.getResourceAsStream("resource");
final File file = new File("d:/temp","fileName");
Files.copy(resource,file.toPath(),StandardCopyOption.REPLACE_EXISTING);
}
}