【发布时间】:2019-03-13 00:21:07
【问题描述】:
我需要使用 OpenXML dataValidation 修改带有下拉列表的 Excel 文件。
由于某种原因,我可以使用下拉菜单创建文件,但无法使用 Open() 方法添加 1。
结果是一个没有下拉菜单的空 excel 文件。
这是我用来创建文件的方法:
public static void addCreateValidator(string path)
{
using (SpreadsheetDocument myDoc = SpreadsheetDocument.Create(path, SpreadsheetDocumentType.Workbook))
{
WorkbookPart workbookpart = myDoc.AddWorkbookPart();
workbookpart.Workbook = new Workbook();
WorksheetPart worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
SheetData sheetData = new SheetData();
worksheetPart.Worksheet = new Worksheet(sheetData);
Sheets sheets = myDoc.WorkbookPart.Workbook.AppendChild(new Sheets());
sheets.AppendChild(new Sheet()
{
Id = myDoc.WorkbookPart.GetIdOfPart(myDoc.WorkbookPart.WorksheetParts.First()),
SheetId = 1,
Name = "Sheet1"
});
DataValidations dataValidations = new DataValidations();
DataValidation dataValidation = new DataValidation()
{
Type = DataValidationValues.List,
AllowBlank = true,
SequenceOfReferences = new ListValue<StringValue>() { InnerText = "A1:A1048576" }
};
Formula1 formula = new Formula1();
formula.Text = "\"FirstChoice,SecondChoice,ThirdChoice\"";
dataValidation.Append(formula);
dataValidations.Append(dataValidation);
worksheetPart.Worksheet.AppendChild(dataValidations);
}
}
这是修改文件的方法:
public static void addValidation(string filepath)
{
using (SpreadsheetDocument myDoc = SpreadsheetDocument.Open(filepath, true))
{
WorkbookPart wbPart = myDoc.WorkbookPart;
var sheetData = new DocumentFormat.OpenXml.Spreadsheet.SheetData();
WorksheetPart worksheetPart =
GetWorksheetPartByName(myDoc, "Sheet1");
DataValidations dataValidations = new DataValidations();
DataValidation dataValidation = new DataValidation()
{
Type = DataValidationValues.List,
AllowBlank = true,
SequenceOfReferences = new ListValue<StringValue>() { InnerText = "h1" }
};
Formula1 formula = new Formula1();
formula.Text = "\"FirstChoice,SecondChoice,ThirdChoice\"";
dataValidation.Append(formula);
dataValidations.Append(dataValidation);
worksheetPart.Worksheet.AppendChild(dataValidations);
//worksheetPart.Worksheet.Save();
}
}
您能看到任何错误或建议解决方法吗?
【问题讨论】:
-
文件打开时是否出现“不可读内容”类型错误?
-
第 1 行第 728 列是
-
嗨@leo,我的回答有帮助吗?