如何创建可编辑的Excel

时间:2017-06-28 06:42:17

标签: c# excel openxml closedxml

我正在创建一个Excel文件:

SpreadsheetDocument document = SpreadsheetDocument.Create(filename, SpreadsheetDocumentType.Workbook)
WorkbookPart workBookPart = document.AddWorkbookPart();
            workBookPart.Workbook = new Workbook();

            WorksheetPart workSheetPart = workBookPart.AddNewPart<WorksheetPart>();
            workSheetPart.Worksheet = new Worksheet();


            Sheets sheets = workBookPart.Workbook.AppendChild(new Sheets());

            Sheet sheet = new Sheet()
            {
                Id = workBookPart.GetIdOfPart(workSheetPart),
                SheetId = 1,
                Name = "Test Sheet"
            };
            sheets.Append(sheet);

            workBookPart.Workbook.Save();

当我打开文件时,它只是ReadOnly,我怎么能让它对用户可编辑?

ClosedXML是优先级,解决方案的替代方式可以是OpenXML

1 个答案:

答案 0 :(得分:1)

您在那里提供的代码会创建一个无效文件而不是只读文件。有两个小问题。首先,每个Worksheet下必须只有一个SheetData元素,其次需要在文档上调用Close方法(直接或间接通过using语句)。

以下代码将为您创建一个可通过显式调用Close

进行编辑的文件
SpreadsheetDocument document = SpreadsheetDocument.Create(filename, SpreadsheetDocumentType.Workbook);
WorkbookPart workBookPart = document.AddWorkbookPart();
workBookPart.Workbook = new Workbook();

WorksheetPart workSheetPart = workBookPart.AddNewPart<WorksheetPart>();
workSheetPart.Worksheet = new Worksheet();

//a worksheet *must* have exactly one child SheetData
workSheetPart.Worksheet.AppendChild(new SheetData());

Sheets sheets = workBookPart.Workbook.AppendChild(new Sheets());

Sheet sheet = new Sheet()
{
    Id = workBookPart.GetIdOfPart(workSheetPart),
    SheetId = 1,
    Name = "Test Sheet"
};
sheets.Append(sheet);

workBookPart.Workbook.Save();

//the document must be closed (and ideally disposed)
document.Close();
document.Dispose();

以下是相同的,但改为使用using语句:

using (SpreadsheetDocument document = SpreadsheetDocument.Create(filename, SpreadsheetDocumentType.Workbook))
{
    WorkbookPart workBookPart = document.AddWorkbookPart();
    workBookPart.Workbook = new Workbook();

    WorksheetPart workSheetPart = workBookPart.AddNewPart<WorksheetPart>();
    workSheetPart.Worksheet = new Worksheet();

    //a worksheet *must* have exactly one child SheetData
    workSheetPart.Worksheet.AppendChild(new SheetData());

    Sheets sheets = workBookPart.Workbook.AppendChild(new Sheets());

    Sheet sheet = new Sheet()
    {
        Id = workBookPart.GetIdOfPart(workSheetPart),
        SheetId = 1,
        Name = "Test Sheet"
    };
    sheets.Append(sheet);

    workBookPart.Workbook.Save();
}

修改

在ClosedXml中执行此操作要简单得多。以下将生成一个等效的工作簿:

using ClosedXML.Excel;
....

var workbook = new XLWorkbook();
var worksheet = workbook.Worksheets.Add("Test Sheet");
workbook.SaveAs(filename);