使用OpenXml SDK 2.0创建Excel文档

17

我用OpenXml SDK 2.0创建了一个Excel文档,现在需要对其进行样式设置,但我不会。

我不知道如何在不同的单元格中设置背景颜色或更改字体大小。

我创建单元格的代码是:

private static Cell CreateTextCell(string header, string text, UInt32Value index)
{
    Cell c = new Cell();
    c.DataType = CellValues.InlineString;
    c.CellReference = header + index;
    InlineString inlineString = new InlineString();
    DocumentFormat.OpenXml.Spreadsheet.Text t = new DocumentFormat.OpenXml.Spreadsheet.Text();
    t.Text = text;
    inlineString.AppendChild(t);
    c.AppendChild(inlineString);
    return c;
} 
3个回答

20
注意: OpenXML 2.0 SDK目前处于CTP阶段,未经许可不能用于Office2010以外的生产环境。
我处理OpenXML SDK的一般方法是创建一个空文档和一个只包含你想学习如何实现的功能(比如背景颜色)的文档,然后使用SDK的OpenXmlDiff查看需要进行哪些更改以实现该功能。
如果您从头开始创建文档,可以使用DocumentReflector生成默认Stylesheet对象的代码,然后添加所需的样式。
从默认值开始:
new Stylesheet(
new Fonts(
    new Font(
        new FontSize() { Val = 10D },
        new Color() { Theme = (UInt32Value)1U },
        new FontName() { Val = "Arial" },
        new FontFamilyNumbering() { Val = 2 })
) { Count = (UInt32Value)1U },
new Fills(
    new Fill(
        new PatternFill() { PatternType = PatternValues.None }),
    new Fill(
        new PatternFill() { PatternType = PatternValues.Gray125 })
) { Count = (UInt32Value)2U },
new Borders(...
...
...
new CellFormats(
new CellFormat() { NumberFormatId = (UInt32Value)0U, FontId = (UInt32Value)0U, FillId = (UInt32Value)0U, BorderId = (UInt32Value)0U, FormatId = (UInt32Value)0U }) { Count = (UInt32Value)1U }, ...

我已经添加了一个大小为12的新字体和一个红色背景的新填充 (索引值为64),并添加了引用新字体和填充索引的新单元格格式。 (确保也更新计数)

new Stylesheet(
    new Fonts(
        new Font(
            new FontSize() { Val = 10D },
            new Color() { Theme = (UInt32Value)1U },
            new FontName() { Val = "Arial" },
            new FontFamilyNumbering() { Val = 2 }),
        new Font(
            new FontSize() { Val = 12D },
            new Color() { Theme = (UInt32Value)1U },
            new FontName() { Val = "Arial" },
            new FontFamilyNumbering() { Val = 2 })
            ) { Count = (UInt32Value)2U },
    new Fills(
        new Fill(
            new PatternFill() { PatternType = PatternValues.None }),
        new Fill(
            new PatternFill() { PatternType = PatternValues.Gray125 }),
        new Fill(
            new PatternFill() { PatternType = PatternValues.Solid, ForegroundColor = new ForegroundColor() { Rgb = "FFFF0000" }, BackgroundColor = new BackgroundColor() { Indexed = 64 } })
            ) { Count = (UInt32Value)3U },
    new Borders(
        new Border(
            new LeftBorder(), new RightBorder(), new TopBorder(), new BottomBorder(), new DiagonalBorder())
    ) { Count = (UInt32Value)1U },
    new CellStyleFormats(
        new CellFormat() { NumberFormatId = (UInt32Value)0U, FontId = (UInt32Value)0U, FillId = (UInt32Value)0U, BorderId = (UInt32Value)0U }
    ) { Count = (UInt32Value)1U },
    new CellFormats(
        new CellFormat() { NumberFormatId = (UInt32Value)0U, FontId = (UInt32Value)0U, FillId = (UInt32Value)0U, BorderId = (UInt32Value)0U, FormatId = (UInt32Value)0U },
        new CellFormat() { NumberFormatId = (UInt32Value)0U, FontId = (UInt32Value)1U, FillId = (UInt32Value)0U, BorderId = (UInt32Value)0U, FormatId = (UInt32Value)0U },
        new CellFormat() { NumberFormatId = (UInt32Value)0U, FontId = (UInt32Value)0U, FillId = (UInt32Value)2U, BorderId = (UInt32Value)0U, FormatId = (UInt32Value)0U }
    ) { Count = (UInt32Value)3U },
    new CellStyles(
        new CellStyle() { Name = "Normal", FormatId = (UInt32Value)0U, BuiltinId = (UInt32Value)0U }
    ) { Count = (UInt32Value)1U },
    new DifferentialFormats() { Count = (UInt32Value)0U },
    new TableStyles() { Count = (UInt32Value)0U, DefaultTableStyle = "TableStyleMedium9", DefaultPivotStyle = "PivotStyleLight16" });

然后,在代码中,我将CellStyle索引应用于我想要格式化的单元格: (单元格A2和A3中已经有数据。单元格A2变大,A3变成红色背景)

SheetData sheetData = worksheetPart.Worksheet.GetFirstChild<SheetData>();
sheetData.Descendants<Row>().Where(r => r.RowIndex == 2U).First().Descendants<Cell>().First().StyleIndex = 1U;
sheetData.Descendants<Row>().Where(r => r.RowIndex == 3U).First().Descendants<Cell>().First().StyleIndex = 2U;

10

非常感谢这篇文章。

在经历了很多挣扎和搜索之后,我终于成功地创建了一个非常易于使用的C#类,它需要一个数据集和一个文件名,并创建一个包含数据集数据的Office 2007 .xlsx文件。

突然之间,将“导出到Excel”功能添加到您的应用程序变得如此简单...

DataSet ds = CreateSampleData();                  //  Your code here !
string excelFilename = "C:\\Sample.xlsx";

CreateExcelFile.CreateExcelDocument(ds, excelFilename);

我已经在以下网站上发布了完整的源代码以及使用示例。

这是一个Visual Studio 2008 C# WinForms应用程序,但如果您正在运行VS2010,则可以让Visual Studio升级此项目。

享受吧。

http://www.mikesknowledgebase.com/pages/CSharp/ExportToExcel.htm


从您的博客中:我没有添加许可证,因为这是免费代码,可以随意使用。 法律现实:缺乏许可证意味着默认版权法适用(免责声明 - 我不是律师)。 - Mars Robertson

2
如何指定单元格样式?
new Cell() { CellReference = "B6", StyleIndex = 11U }

这里的"11U"是StylesPart.Stylesheet.CellFormats的基于零的索引,其中每个CellFormat都定义了NumberFormat、Font、Fill和Border样式的组合。

你不必通过编程添加所有的样式,而是可以创建一个包含所需格式的模板xlsx文件,然后在程序中指定样式索引即可。


你好,Hailaing Wang。根据你提到的内容,我不确定如何修改单元格的样式。你是如何得到StyleIndex = 11U的?在我的情况下,我需要让单元格有边框,并且需要它有蓝色背景。你能否回复一下这个链接:https://dev59.com/o2Uo5IYBdhLWcg3wvRpF。非常感谢! - Nate Pet

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接