我正在创建一个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
答案 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);