该进程无法访问该文件,因为它正由使用电子表格文档的另一个进程使用

本文关键字:进程 电子表格 文档 另一个 访问 文件 因为 | 更新日期: 2023-09-27 18:34:31

请帮助我解决问题,当我保存 excel 文件时抛出此错误,我将 excel 文件转换为 zip 文件。

zip.Save(@"" + root + "/" + "" + userid + ".zip");

进程无法访问该文件,因为它正被另一个进程使用我的代码如下

  using (SpreadsheetDocument document = SpreadsheetDocument.Create(excelFilename, SpreadsheetDocumentType.Workbook))
        {
             WriteExcelFile(ds, document);
        }
private static void WriteExcelFile(DataSet ds, SpreadsheetDocument spreadsheet)
{
    spreadsheet.AddWorkbookPart();
    spreadsheet.WorkbookPart.Workbook = new DocumentFormat.OpenXml.Spreadsheet.Workbook();
    spreadsheet.WorkbookPart.Workbook.Append(new BookViews(new WorkbookView()));
    //  If we don't add a "WorkbookStylesPart", OLEDB will refuse to connect to this .xlsx file !
    WorkbookStylesPart workbookStylesPart = spreadsheet.WorkbookPart.AddNewPart<WorkbookStylesPart>("rIdStyles");
    Stylesheet stylesheet = new Stylesheet();
    workbookStylesPart.Stylesheet = stylesheet;
    //  Loop through each of the DataTables in our DataSet, and create a new Excel Worksheet for each.
    uint worksheetNumber = 1;
    foreach (DataTable dt in ds.Tables)
    {
        //  For each worksheet you want to create
        string workSheetID = "rId" + worksheetNumber.ToString();
        string worksheetName = dt.TableName;
        WorksheetPart newWorksheetPart = spreadsheet.WorkbookPart.AddNewPart<WorksheetPart>();
        newWorksheetPart.Worksheet = new DocumentFormat.OpenXml.Spreadsheet.Worksheet();
        // create sheet data
        newWorksheetPart.Worksheet.AppendChild(new DocumentFormat.OpenXml.Spreadsheet.SheetData());
        // save worksheet
        WriteDataTableToExcelWorksheet(dt, newWorksheetPart);
        newWorksheetPart.Worksheet.Save();
        // create the worksheet to workbook relation
        if (worksheetNumber == 1)
            spreadsheet.WorkbookPart.Workbook.AppendChild(new DocumentFormat.OpenXml.Spreadsheet.Sheets());
        spreadsheet.WorkbookPart.Workbook.GetFirstChild<DocumentFormat.OpenXml.Spreadsheet.Sheets>().AppendChild(new DocumentFormat.OpenXml.Spreadsheet.Sheet()
        {
            Id = spreadsheet.WorkbookPart.GetIdOfPart(newWorksheetPart),
            SheetId = (uint)worksheetNumber,
            Name = dt.TableName
        });
        worksheetNumber++;
    }
    spreadsheet.WorkbookPart.Workbook.Save();
}

该进程无法访问该文件,因为它正由使用电子表格文档的另一个进程使用

我看到您已经保存了文档,但尚未关闭它。因此,它仍将与电子表格文档对象一起打开。

保存文档后添加以下行。

spreadsheet.WorkbookPart.Workbook.Close();

如果它没有帮助,请提供完整的代码,以便我们可以进一步研究它。祝你好运。

我认为在尝试将它们放入 Zip 文件中之前,您不会关闭所有工作簿。把它放在方法的末尾:

private static void WriteExcelFile(DataSet ds, SpreadsheetDocument spreadsheet)
{
...
spreadsheet.WorkbookPart.Workbook.Close();
}