如何使用OpenXML将列插入Excel工作表

时间:2014-06-04 17:40:50

标签: .net openxml openxml-sdk

我提供了一个Excel工作簿(xlsx)来生成报告。 在某些情况下,我需要插入列。这是我正在尝试的代码。它运行正常,但不在工作表中插入新列: 我怎么能做到这一点?

using (SpreadsheetDocument document = SpreadsheetDocument.Open(outputPath, true)){
    Sheet sheet1 = document.WorkbookPart.Workbook.Descendants<Sheet>().Single( s => s.Name == "Balance" );

    Worksheet workSheet1 = ( (WorksheetPart)document.WorkbookPart.GetPartById( sheet2.Id ) ).Worksheet;

    Columns cs = workSheet1.GetFirstChild<Columns>();                          
    Column c = new Column()
    {
        Min = (UInt32Value)1U,
        Max = (UInt32Value)1U,
        Width = 44.33203125D,
        CustomWidth = true
    };
    cs.Append( c );
}

1 个答案:

答案 0 :(得分:2)

您的代码所做的是调整第一列的尺寸。不插入新的。 根据我对OpenXML的理解,您需要遍历行集合并调整每个单元格的单元格引用。

这将涉及遍历行集合,然后每行迭代单元格集合。获取每个单元格的单元格引用,其格式为&#34; B1&#34;,解析它,增加列部分以产生例如&#34; C1&#34;。 这仍然会让您了解如何更新公式引用。祝你好运! : - )

我能想到的三种选择:

1)尝试ClosedXML之类的东西 - 我从来没有用过这个,所以不知道它会有多好用。

2)使用VSTO而不是OpenXML编写Excel加载项。但这似乎首先打败了OpenXML的目标。

3)横向思考。在工作簿中创建一个新工作表,根据需要为您添加第一列信息,并为原始&#34; Balance&#34;中的每个单元格添加信息。 sheet在新工作表中创建一个新单元格,其中包含&#34; Balance!A1&#34;。行的公式 这将是我的首选方法,因为它保留了原始格式的源表格,并且您的报表可以从新工作表中读取,您还可以在其中添加所需的任何其他计算列。
创建新工作表可以提供更大的灵活性。

您可以添加类似于:

的公式单元格
string sourcecell = ...; // read this from the cell reference of the original cell
string newcell = ...;  // parse the original cell ref and increment the column

row.Append(new Cell(
    new CellFormula() { 
        FormulaType = CellFormulaValues.Normal, 
        Text = string.Format("Balance!({0})", sourcecell)
    },
    new CellValue("0.00")
    ) { CellReference = newcell, StyleIndex = 0 }
);

当我们最近做类似的事情时,我发现这两个链接很有用:
Creating an OpenXML spreadsheet from scratch
Styling an OpenXML spreadsheet

相关问题