该进程无法访问该文件,因为其他进程正在使用电子表格文档

时间:2014-12-18 07:33:49

标签: c# asp.net excel

请帮我解决问题,当我保存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();
}

2 个答案:

答案 0 :(得分:0)

我发现您已保存文档,但尚未关闭它。因此,它仍将使用 spreadsheetdocument 对象打开。

保存文档后添加以下行。

spreadsheet.WorkbookPart.Workbook.Close();

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

答案 1 :(得分:0)

我认为在尝试将它们放入Zip-File之前,您并未关闭所有工作簿。 把它放在方法的末尾:

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