1

我的代码中有以下方法 ( createAdditionalSheetsInExcel),它尝试为特定场景 ( runOutputNumber > 1) 创建额外的工作表。它最终创建了一个 excel,但问题是当您尝试打开 excel 时,您最终会收到以下错误:

java代码中workBookObj.cloneSheet(index,sheetName)没有引发错误,但是当我尝试打开excel文件时,出现以下错误:

我试图删除工作表中表格的格式,然后错误消失。所以肯定是和sheet里面表格的格式有关。

private static void createAdditionalSheetsInExcel(String tempOutputFileName, String outputFileName, int runOutputNumber) throws IOException {

    FileInputStream fileIn = new FileInputStream(tempOutputFileName);
    XSSFWorkbook workBookObj = new XSSFWorkbook(fileIn);
    workBookObj.setWorkbookType(XSSFWorkbookType.XLSM);

    runOutputNumber = 2;//Hard coded for clarification
    if (runOutputNumber > 1) {

        int initialNoOfSheets = workBookObj.getNumberOfSheets();

        for (int runIndex = 2; runIndex <= runOutputNumber; runIndex++) {

            for (int index = 0; index < initialNoOfSheets; index++) {
                XSSFSheet sheet = workBookObj.getSheetAt(index);

                String sheetName = sheet.getSheetName().trim()
                                    .substring(0, sheet.getSheetName().length() - 1) + runIndex;
                workBookObj.cloneSheet(index, sheetName);
            }
        }
    }

    FileOutputStream fileOut = new FileOutputStream(outputFileName);
    workBookObj.write(fileOut);

    fileOut.close();
    workBookObj.close();
    deleteTempExcel(tempOutputFileName);
}

excel尝试打开时出错:

我们发现“abc.xlsm”中的某些内容存在问题。你想尽可能多地恢复吗?如果您信任此工作簿的来源,请单击“是”。

错误:打开excel文件后:

修复的记录:来自 /xl/tables/table1.xml 部分的表(表)

4

2 回答 2

1

在此处输入图像描述

最后使用 jacob api 并通过更改模板解决了这个问题。问题是在 Excel 中定义的局部变量,我可以通过转到(公式 - > 名称管理器)访问并删除该变量。即使在删除该变量后,我也无法让它与 Apache POI 一起使用,因此最终使用 Jacob api。代码如下:

    package com.ford.ltdrive.model.output.excel.excelenum;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

public class CloneSheet {

    public void backup(String filepath) {
        try {
            Date d = new Date();
            String dateString = (d.getYear() + 1900) + "_" + d.getMonth() + "_" + d.getDate();
           // String backupfilepath = filepath.replace(".xlsm", "_backup_" + dateString + ".xlsm");
            //Path copied = Paths.get(backupfilepath);
            Path copied1 = Paths.get(filepath + "_tmp");
            Path originalPath = Paths.get(filepath);
           // Files.copy(originalPath, copied, StandardCopyOption.REPLACE_EXISTING);
            Files.copy(originalPath, copied1, StandardCopyOption.REPLACE_EXISTING);
            Files.delete(Paths.get(filepath));
        } catch (IOException ex) {
            Logger.getLogger(CloneSheet.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    public void cloneSheets(String xlsfile, java.util.List<String> list,int copynum) {
        ActiveXComponent app = new ActiveXComponent("Excel.Application");
        try {
            backup(xlsfile);

            app.setProperty("Visible", new Variant(false));
            Dispatch excels = app.getProperty("Workbooks").toDispatch();
            Dispatch excel = Dispatch.invoke(
                    excels,
                    "Open",
                    Dispatch.Method,
                    new Object[]{xlsfile + "_tmp", new Variant(false),
                        new Variant(true)}, new int[1]).toDispatch();
            //Dispatch sheets = Dispatch.get((Dispatch) excel, "Worksheets").toDispatch();
            int sz = list.size();//"Angle_1pc_SBC_R1"
            for (int i = 0; i < sz; i++) {
                Dispatch sheet = Dispatch.invoke(excel, "Worksheets", Dispatch.Get,
                        new Object[]{list.get(i)}, new int[1]).toDispatch();//Whatever sheet you    //wanted the new sheet inserted after

                //Dispatch workbooksTest = app.getProperty("Sheets").toDispatch();//Get the workbook
                //Dispatch sheet2 = Dispatch.call(workbooksTest, "Add").toDispatch();
                for(int k=0;k<copynum -1;k++)
                {
                    Dispatch.call(sheet, "Copy", sheet);
                }
            }
            //Moves the sheet behind the desired sheet
            Dispatch.invoke(excel, "SaveAs", Dispatch.Method, new Object[]{xlsfile, new Variant(52)}, new int[1]);
            Variant f = new Variant(false);
            Dispatch.call(excel, "Close", f);
            Files.delete(Paths.get(xlsfile + "_tmp"));

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            app.invoke("Quit", new Variant[]{});
        }
    }
   /* public static void main(String args[])
    {
        java.util.ArrayList<String> list = new java.util.ArrayList();
        list.add("Angle_1pc_SBC_R1");
        new CloneSheet().cloneSheets("C:\\LTDrive2_4\\Excel\\Test.xlsm", list, 2);
    }*/
}
于 2019-08-07T16:53:39.760 回答
0

have similar issue. I have a Threads that was writing to an excel file .

solve it by adding synchronized to the function that I use to write into the excel

于 2022-01-02T12:57:58.743 回答