【发布时间】:2014-06-05 18:34:49
【问题描述】:
我有一个预定义的 Excel 工作簿,其中包含所有工作表,我需要向其中写入内容。我成功写入单元格。
问题出在我需要向其中添加三列的特定工作表中。在下面的代码中,首先我获取Worksheet,然后我继续添加列。这段代码运行良好,我的意思是,没有抛出异常,但是当我尝试打开 Excel 文件时出现错误,指出有一些内容无法读取,并且此特定工作表的所有内容都已清除。
我知道问题出在此操作上,因为如果我注释掉那些添加列的行,工作簿就会很好地打开,而我从代码中写入的所有单元格值都在原位。
这是相关代码,出于测试目的,我尝试添加 3 列:
using (SpreadsheetDocument document = SpreadsheetDocument.Open(outputPath, true)){
Sheet sheet2 = document.WorkbookPart.Workbook.Descendants<Sheet>().Single( s => s.Name == "Miscellaneous Credit" );
Worksheet workSheet2 = ( (WorksheetPart)document.WorkbookPart.GetPartById( sheet2.Id ) ).Worksheet;
Columns cs = new Columns();
for ( var y = 1; y <= 3; y++ ) {
Column c = new Column()
{
Min = (UInt32Value)1U,
Max = (UInt32Value)1U,
Width = 44.33203125D,
CustomWidth = true
};
cs.Append( c );
}
workSheet2.Append( cs );
}
编辑:根据克里斯对列概念的解释
using (SpreadsheetDocument document = SpreadsheetDocument.Open(outputPath, true)){
Sheet sheet2 = document.WorkbookPart.Workbook.Descendants<Sheet>().Single( s => s.Name == "Miscellaneous Credit" );
Worksheet workSheet2 = ( (WorksheetPart)document.WorkbookPart.GetPartById( sheet2.Id ) ).Worksheet;
// Check if the column collection exists
Columns cs = workSheet2.Elements<Columns>().FirstOrDefault();
if ( ( cs == null ) ) {
// If Columns appended to worksheet after sheetdata Excel will throw an error.
SheetData sd = workSheet2.Elements<SheetData>().FirstOrDefault();
if ( ( sd != null ) ) {
cs = workSheet2.InsertBefore( new Columns(), sd );
}
else {
cs = new Columns();
workSheet2.Append( cs );
}
}
//create a column object to define the width of columns 1 to 3
Column c = new Column
{
Min = (UInt32Value)1U,
Max = (UInt32Value)3U,
Width = 44.33203125,
CustomWidth = true
};
cs.Append( c );
}
【问题讨论】:
标签: c# .net openxml openxml-sdk