65.9K
CodeProject 正在变化。 阅读更多。
Home

使用 C# 和 Open XML SDK 2.0 for Microsoft Office 创建 Excel 2007 文档

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.72/5 (26投票s)

2010 年 7 月 30 日

CPOL

5分钟阅读

viewsIcon

311757

downloadIcon

10470

演示了如何使用 C# 和 Open XML SDK 2.0 for Microsoft Office 创建 Excel 2007 文档。

Spreadsheet.jpg

引言

许多业务用户希望将他们的业务对象导出到 Microsoft Excel 电子表格,因为这能够以业务主管能够理解的方式呈现和处理数据。

在本文中,我们将学习如何使用 C# 和 Open XML SDK 2.0 for Microsoft Office 从对象列表中轻松创建 Excel 电子表格文档。

背景

Open XML Formats Developer Group 的成立旨在为有兴趣使用 ECMA International 开发的 Office Open XML 文件格式的开发人员提供一个技术论坛。Office 2007 使用此格式创建 Word、Excel 等。Open XML Formats Developer Group 的默认网站是 http://openxmldeveloper.org/default.aspx

Microsoft 提供的 Open XML SDK 2.0 简化了操作 Open XML 包以及包内底层 Open XML 架构元素的工作。Open XML 应用程序编程接口 (API) 封装了开发人员在 Open XML 包上执行的许多常见任务。Open XML SDK 2.0 的下载链接是 http://www.microsoft.com/downloads/details.aspx?FamilyID=C6E744E5-36E9-45F5-8D8C-331DF206E0D0&displaylang=en

过去,要在 C# 应用程序中将数据导出到 Excel 电子表格,我们不得不使用 XSLT 转换或 COM 互操作。Open XML SDK 是一个 .NET 对象,我们可以使用它,而无需学习所有 XSLT,并且它易于使用且可靠。使用 COM 互操作也不那么容易,而且我们需要处理 Excel 2007 和 Excel 2010 的不同版本的 Excel 对象。有时我们只想构建一个服务来从服务器导出电子表格。使用 COM 互操作意味着我们需要在服务器上安装部分 Excel COM 对象才能使其正常工作。Open XML SDK 2.0 在我们的服务器上不需要任何 Excel COM 对象。

目的

将业务对象导出到电子表格的目的是为了业务用户,例如,当我们在网格中显示数据列表时,用户希望将其放入电子表格以确定“假如”场景。这对于只想在电子表格中获取这些数据的财务分析师非常有用。

Using the Code

首先,您需要使用 Visual Studio 2010 创建一个控制台应用程序。

要使用这些类,您必须将 Open XML SDK 2.0 的 DocumentFormat.OpenXml 库和 WindowsBase 添加到项目中作为引用;在 Visual Studio 中添加引用非常直接。首先,您必须安装 Microsoft 提供的 Open XML SDK 2.0,它将安装到C:\Program Files\Open XML SDK

右键单击解决方案资源管理器中的项目,您应该会看到“添加引用”选项。选择后,单击“浏览”选项卡,然后浏览到C:\Program Files\Open XML SDK\V2.0\lib 文件夹并选择DocumentFormat.OpenXml.dll。您还需要从 .NET 选项卡中选择 WindowBaseSystem.Drawing

您可以将相应的类复制到创建的文件中。最后,将 void MainPackage 类复制到Program.cs

让我们回顾一下类

我们创建了CustomStylesheet.csCustomColumn.csCustomCell.csExcelHelper.cs

自定义样式表

我们将尝试创建一个自定义样式表,其中包含如下最常用的格式:

  • 它有两种字体:普通和标题,这两种字体都有两个索引。
  • 它有四种填充类型,包括空白和灰色。
  • 它有三种边框类型:空白、四边和顶部/底部。
  • 最后,它有十二种单元格格式,用于数字、日期和文本,并且单元格中的每个 StyleIndex 都使用索引进行正确格式化。

您可以添加更多样式来格式化单元格。单元格样式索引必须分配正确的索引。正如您所看到的,项目中的自定义单元格使用索引来格式化数字和日期。

//CustomStylesheet.cs
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Spreadsheet;
namespace CreateExcelSpreadsheet
{
    public class CustomStylesheet : Stylesheet
    {
        public CustomStylesheet()
        {
            var fonts = new Fonts();
            var font = new DocumentFormat.OpenXml.Spreadsheet.Font();
            var fontName = new FontName {Val = StringValue.FromString("Arial")};
            var fontSize = new FontSize {Val = DoubleValue.FromDouble(11)};
            font.FontName = fontName;
            font.FontSize = fontSize;
            fonts.Append(font);
            //Font Index 1
            font = new DocumentFormat.OpenXml.Spreadsheet.Font();
            fontName = new FontName {Val = StringValue.FromString("Arial")};
            fontSize = new FontSize {Val = DoubleValue.FromDouble(12)};
            font.FontName = fontName;
            font.FontSize = fontSize;
            font.Bold = new Bold();
            fonts.Append(font);
            fonts.Count = UInt32Value.FromUInt32((uint)fonts.ChildElements.Count);
            var fills = new Fills();
            var fill = new Fill();
            var patternFill = new PatternFill {PatternType = PatternValues.None};
            fill.PatternFill = patternFill;
            fills.Append(fill);
            fill = new Fill();
            patternFill = new PatternFill {PatternType = PatternValues.Gray125};
            fill.PatternFill = patternFill;
            fills.Append(fill);
            //Fill index  2
            fill = new Fill();
            patternFill = new PatternFill {PatternType = PatternValues.Solid, 
                                           ForegroundColor = new ForegroundColor()};
            patternFill.ForegroundColor = 
               TranslateForeground(System.Drawing.Color.LightBlue);
            patternFill.BackgroundColor = 
                new BackgroundColor {Rgb = patternFill.ForegroundColor.Rgb};
            fill.PatternFill = patternFill;
            fills.Append(fill);
            //Fill index  3
            fill = new Fill();
            patternFill = new PatternFill {PatternType = PatternValues.Solid, 
                              ForegroundColor = new ForegroundColor()};
            patternFill.ForegroundColor = 
               TranslateForeground(System.Drawing.Color.DodgerBlue);
            patternFill.BackgroundColor = 
               new BackgroundColor {Rgb = patternFill.ForegroundColor.Rgb};
            fill.PatternFill = patternFill;
            fills.Append(fill);
            fills.Count = UInt32Value.FromUInt32((uint)fills.ChildElements.Count);
            var borders = new Borders();
            var border = new Border
                        {
                            LeftBorder = new LeftBorder(),
                            RightBorder = new RightBorder(),
                            TopBorder = new TopBorder(),
                            BottomBorder = new BottomBorder(),
                            DiagonalBorder = new DiagonalBorder()
                        };
            borders.Append(border);
            //All Boarder Index 1
            border = new Border
                         {
                             LeftBorder = new LeftBorder {Style = BorderStyleValues.Thin},
                             RightBorder = new RightBorder {Style = BorderStyleValues.Thin},
                             TopBorder = new TopBorder {Style = BorderStyleValues.Thin},
                             BottomBorder = new BottomBorder {Style = BorderStyleValues.Thin},
                             DiagonalBorder = new DiagonalBorder()
                         };
            borders.Append(border);
            //Top and Bottom Boarder Index 2
            border = new Border
            {
                LeftBorder = new LeftBorder(),
                RightBorder = new RightBorder (),
                TopBorder = new TopBorder { Style = BorderStyleValues.Thin },
                BottomBorder = new BottomBorder { Style = BorderStyleValues.Thin },
                DiagonalBorder = new DiagonalBorder()
            };
            borders.Append(border);
            borders.Count = UInt32Value.FromUInt32((uint)borders.ChildElements.Count);
            var cellStyleFormats = new CellStyleFormats();
            var cellFormat = new CellFormat {NumberFormatId = 0, 
                                 FontId = 0, FillId = 0, BorderId = 0};
            cellStyleFormats.Append(cellFormat);
            cellStyleFormats.Count = 
               UInt32Value.FromUInt32((uint)cellStyleFormats.ChildElements.Count);
            uint iExcelIndex = 164;
            var numberingFormats = new NumberingFormats();
            var cellFormats = new CellFormats();
            cellFormat = new CellFormat {NumberFormatId = 0, FontId = 0, 
                             FillId = 0, BorderId = 0, FormatId = 0};
            cellFormats.Append(cellFormat);
            var nformatDateTime = new NumberingFormat
                     {
                         NumberFormatId = UInt32Value.FromUInt32(iExcelIndex++),
                         FormatCode = StringValue.FromString("dd/mm/yyyy hh:mm:ss")
                     };
            numberingFormats.Append(nformatDateTime);
            var nformat4Decimal = new NumberingFormat
                     {
                         NumberFormatId = UInt32Value.FromUInt32(iExcelIndex++),
                         FormatCode = StringValue.FromString("#,##0.0000")
                     };
            numberingFormats.Append(nformat4Decimal);
            var nformat2Decimal = new NumberingFormat
                      {
                          NumberFormatId = UInt32Value.FromUInt32(iExcelIndex++),
                          FormatCode = StringValue.FromString("#,##0.00")
                      };
            numberingFormats.Append(nformat2Decimal);
            var nformatForcedText = new NumberingFormat
                       {
                           NumberFormatId = UInt32Value.FromUInt32(iExcelIndex),
                           FormatCode = StringValue.FromString("@")
                       };
            numberingFormats.Append(nformatForcedText);
            // index 1
            // Cell Standard Date format 
            cellFormat = new CellFormat
                 {
                     NumberFormatId = 14,
                     FontId = 0,
                     FillId = 0,
                     BorderId = 0,
                     FormatId = 0,
                     ApplyNumberFormat = BooleanValue.FromBoolean(true)
                 };
            cellFormats.Append(cellFormat);
            // Index 2
            // Cell Standard Number format with 2 decimal placing
            cellFormat = new CellFormat
                 {
                     NumberFormatId = 4,
                     FontId = 0,
                     FillId = 0,
                     BorderId = 0,
                     FormatId = 0,
                     ApplyNumberFormat = BooleanValue.FromBoolean(true)
                 };
            cellFormats.Append(cellFormat);
            // Index 3
            // Cell Date time custom format
            cellFormat = new CellFormat
                 {
                     NumberFormatId = nformatDateTime.NumberFormatId,
                     FontId = 0,
                     FillId = 0,
                     BorderId = 0,
                     FormatId = 0,
                     ApplyNumberFormat = BooleanValue.FromBoolean(true)
                 };
            cellFormats.Append(cellFormat);
            // Index 4
            // Cell 4 decimal custom format
            cellFormat = new CellFormat
                 {
                     NumberFormatId = nformat4Decimal.NumberFormatId,
                     FontId = 0,
                     FillId = 0,
                     BorderId = 0,
                     FormatId = 0,
                     ApplyNumberFormat = BooleanValue.FromBoolean(true)
                 };
            cellFormats.Append(cellFormat);
            // Index 5
            // Cell 2 decimal custom format
            cellFormat = new CellFormat
                 {
                     NumberFormatId = nformat2Decimal.NumberFormatId,
                     FontId = 0,
                     FillId = 0,
                     BorderId = 0,
                     FormatId = 0,
                     ApplyNumberFormat = BooleanValue.FromBoolean(true)
                 };
            cellFormats.Append(cellFormat);
            // Index 6
            // Cell forced number text custom format
            cellFormat = new CellFormat
                 {
                     NumberFormatId = nformatForcedText.NumberFormatId,
                     FontId = 0,
                     FillId = 0,
                     BorderId = 0,
                     FormatId = 0,
                     ApplyNumberFormat = BooleanValue.FromBoolean(true)
                 };
            cellFormats.Append(cellFormat);
            // Index 7
            // Cell text with font 12 
            cellFormat = new CellFormat
                 {
                     NumberFormatId = nformatForcedText.NumberFormatId,
                     FontId = 1,
                     FillId = 0,
                     BorderId = 0,
                     FormatId = 0,
                     ApplyNumberFormat = BooleanValue.FromBoolean(true)
                 };
            cellFormats.Append(cellFormat);
            // Index 8
            // Cell text
            cellFormat = new CellFormat
                 {
                     NumberFormatId = nformatForcedText.NumberFormatId,
                     FontId = 0,
                     FillId = 0,
                     BorderId = 1,
                     FormatId = 0,
                     ApplyNumberFormat = BooleanValue.FromBoolean(true)
                 };
            cellFormats.Append(cellFormat);
            // Index 9
            // Coloured 2 decimal cell text
            cellFormat = new CellFormat
                     {
                         NumberFormatId = nformat2Decimal.NumberFormatId,
                         FontId = 0,
                         FillId = 2,
                         BorderId = 2,
                         FormatId = 0,
                         ApplyNumberFormat = BooleanValue.FromBoolean(true)
                     };
            cellFormats.Append(cellFormat);
            // Index 10
            // Coloured cell text
            cellFormat = new CellFormat
                     {
                         NumberFormatId = nformatForcedText.NumberFormatId,
                         FontId = 0,
                         FillId = 2,
                         BorderId = 2,
                         FormatId = 0,
                         ApplyNumberFormat = BooleanValue.FromBoolean(true)
                     };
            cellFormats.Append(cellFormat);
            // Index 11
            // Coloured cell text
            cellFormat = new CellFormat
                 {
                     NumberFormatId = nformatForcedText.NumberFormatId,
                     FontId = 1,
                     FillId = 3,
                     BorderId = 2,
                     FormatId = 0,
                     ApplyNumberFormat = BooleanValue.FromBoolean(true)
                 };
            cellFormats.Append(cellFormat);
            numberingFormats.Count = 
              UInt32Value.FromUInt32((uint)numberingFormats.ChildElements.Count);
            cellFormats.Count = UInt32Value.FromUInt32((uint)cellFormats.ChildElements.Count);
            this.Append(numberingFormats);
            this.Append(fonts);
            this.Append(fills);
            this.Append(borders);
            this.Append(cellStyleFormats);
            this.Append(cellFormats);
            var css = new CellStyles();
            var cs = new CellStyle {Name = StringValue.FromString("Normal"), 
                                    FormatId = 0, BuiltinId = 0};
            css.Append(cs);
            css.Count = UInt32Value.FromUInt32((uint)css.ChildElements.Count);
            this.Append(css);
            var dfs = new DifferentialFormats {Count = 0};
            this.Append(dfs);
            var tss = new TableStyles
                  {
                      Count = 0,
                      DefaultTableStyle = StringValue.FromString("TableStyleMedium9"),
                      DefaultPivotStyle = StringValue.FromString("PivotStyleLight16")
                  };
            this.Append(tss);
        }
        private static ForegroundColor TranslateForeground(System.Drawing.Color fillColor)
        {
           return new ForegroundColor()
           {
               Rgb = new HexBinaryValue()
                     {
                         Value =
                             System.Drawing.ColorTranslator.ToHtml(
                             System.Drawing.Color.FromArgb(
                                 fillColor.A,
                                 fillColor.R,
                                 fillColor.G,
                                 fillColor.B)).Replace("#", "")
                     }
           };
        }
    }
}

自定义列类

我们创建了一个自定义列,它允许我们调整大小以适应标题,因为有时标准的宽度不足以显示单元格中的所有文本。

//CustomColumn.cs
using System;
using DocumentFormat.OpenXml.Spreadsheet;
namespace CreateExcelSpreadsheet
{
    public class CustomColumn : Column
    {
        public CustomColumn(UInt32 startColumnIndex, 
               UInt32 endColumnIndex, double columnWidth)
        {
            this.Min = startColumnIndex;
            this.Max = endColumnIndex;
            this.Width = columnWidth;
            this.CustomWidth = true;
        }
    }
}

自定义单元格类

我们创建自定义单元格来根据以下类型格式化单元格:

  • TextCell - 用于文本字段。
  • NumberCell - 用于整数字段。
  • FormatedNumberCell - 用于十进制或双精度数,并格式化为 2 位小数。
  • DateCell - 用于日期,并格式化为 dd/mm/yyyy,因为在电子表格中它是一个数字值,并依赖于格式。
  • FormulaCell - 用于公式,本例中用作列值的总和。
  • HeaderCell - 用于文本字段,该字段是标题。

您可以进一步增强代码的另一个选项是允许两种不同的格式:一种用于带有两位小数点的格式化数字单元格,另一种用于带有四位小数点的格式化数字单元格。

//CustomCells

using System;
using DocumentFormat.OpenXml.Spreadsheet;
namespace CreateExcelSpreadsheet
{
    public class TextCell : Cell
    {
        public TextCell(string header, string text, int index)
        {
            this.DataType = CellValues.InlineString;
            this.CellReference = header + index;
            //Add text to the text cell.
            this.InlineString = new InlineString { Text = new Text { Text = text } };
        }
    }
    public class NumberCell : Cell
    {
        public NumberCell(string header, string text, int index)
        {
            this.DataType = CellValues.Number;
            this.CellReference = header + index;
            this.CellValue = new CellValue(text);
        }
    }
    public class FormatedNumberCell : NumberCell
    {
        public FormatedNumberCell(string header, string text, int index)
            : base(header, text, index)
        {
            this.StyleIndex = 2;
        }
    }
    public class DateCell : Cell
    {
        public DateCell(string header, DateTime dateTime, int index)
        {
            this.DataType = CellValues.Date;
            this.CellReference = header + index;
            this.StyleIndex = 1;
            this.CellValue = new CellValue { Text = dateTime.ToOADate().ToString() }; ;
        }
    }
    public class FomulaCell : Cell
    {
        public FomulaCell(string header, string text, int index)
        {
            this.CellFormula = new CellFormula { CalculateCell = true, Text = text };
            this.DataType = CellValues.Number;
            this.CellReference = header + index;
            this.StyleIndex = 2;
        }
    }
    public class HeaderCell : TextCell
    {
        public HeaderCell(string header, string text, int index) : 
               base(header, text, index)
        {
            this.StyleIndex = 11;
        }
    }
}

Excel 助手类

我们创建了一个主助手方法,我们可以将要创建的电子表格的完整路径文件名、电子表格中行的对象列表、工作表名称(更改 Sheet 1)以及第一行的标题名称列表传递进去。

//ExcelHelper.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
namespace CreateExcelSpreadsheet
{
    class ExcelHelper
    {
        /// <summary>
        /// Write excel file of a list of object as T
        /// Assume that maximum of 24 columns 
        /// </summary>
        /// <typeparam name="T">Object type to pass in</typeparam>
        /// <param name="fileName">Full path of the file name of excel spreadsheet</param>
        /// <param name="objects">list of the object type</param>
        /// <param name="sheetName">Sheet names of Excel File</param>
        /// <param name="headerNames">Header names of the object</param>
        public void Create<T>(
            string fileName,
            List<T> objects,
            string sheetName,
            List<string> headerNames)
        {
            //Open the copied template workbook. 
            using (SpreadsheetDocument myWorkbook = 
                   SpreadsheetDocument.Create(fileName, 
                   SpreadsheetDocumentType.Workbook))
            {
                WorkbookPart workbookPart = myWorkbook.AddWorkbookPart();
                var worksheetPart = workbookPart.AddNewPart<WorksheetPart>();
                // Create Styles and Insert into Workbook
                var stylesPart = 
                    myWorkbook.WorkbookPart.AddNewPart<WorkbookStylesPart>();
                Stylesheet styles = new CustomStylesheet();
                styles.Save(stylesPart);
                string relId = workbookPart.GetIdOfPart(worksheetPart);
                var workbook = new Workbook();
                var fileVersion = 
                    new FileVersion { ApplicationName = 
                    "Microsoft Office Excel" };
                var worksheet = new Worksheet();
                int numCols = headerNames.Count;
                var columns = new Columns();
                for (int col = 0; col < numCols; col++)
                {
                    int width = headerNames[col].Length + 5;
                    Column c = new CustomColumn((UInt32)col + 1, 
                                  (UInt32)numCols + 1, width);
                    columns.Append(c);
                }
                worksheet.Append(columns);
                var sheets = new Sheets();
                var sheet = new Sheet { Name = sheetName, SheetId = 1, Id = relId };
                sheets.Append(sheet);
                workbook.Append(fileVersion);
                workbook.Append(sheets);
                SheetData sheetData = CreateSheetData(objects, headerNames);
                worksheet.Append(sheetData);
                worksheetPart.Worksheet = worksheet;
                worksheetPart.Worksheet.Save();
                myWorkbook.WorkbookPart.Workbook = workbook;
                myWorkbook.WorkbookPart.Workbook.Save();
                myWorkbook.Close();
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T">Object type to pass in</typeparam>
        /// <param name="objects">list of the object type</param>
        /// <param name="headerNames">Header names of the object</param>
        /// <returns></returns>
        private static SheetData CreateSheetData<T>(List<T> objects, 
                       List<string> headerNames)
        {
            var sheetData = new SheetData();
            if (objects != null)
            {
                //Get fields names of object
                List<string> fields = GetPropertyInfo<T>();
                //Get a list of A to Z
                var az = new List<Char>(Enumerable.Range('A', 'Z' - 
                                      'A' + 1).Select(i => (Char)i).ToArray());
                //A to E number of columns 
                List<Char> headers = az.GetRange(0, fields.Count);
                int numRows = objects.Count;
                int numCols = fields.Count;
                var header = new Row();
                int index = 1;
                header.RowIndex = (uint)index;
                for (int col = 0; col < numCols; col++)
                {
                    var c = new HeaderCell(headers[col].ToString(), 
                                           headerNames[col], index);
                    header.Append(c);
                }
                sheetData.Append(header);
                for (int i = 0; i < numRows; i++)
                {
                    index++;
                    var obj1 = objects[i];
                    var r = new Row { RowIndex = (uint)index };
                    for (int col = 0; col < numCols; col++)
                    {
                        string fieldName = fields[col];
                        PropertyInfo myf = obj1.GetType().GetProperty(fieldName);
                        if (myf != null)
                        {
                            object obj = myf.GetValue(obj1, null);
                            if (obj != null)
                            {
                                if (obj.GetType() == typeof(string))
                                {
                                    var c = new TextCell(headers[col].ToString(), 
                                                obj.ToString(), index);
                                    r.Append(c);
                                }
                                else if (obj.GetType() == typeof(bool))
                                {
                                    string value = 
                                      (bool)obj ? "Yes" : "No";
                                    var c = new TextCell(headers[col].ToString(), 
                                                         value, index);
                                    r.Append(c);
                                }
                                else if (obj.GetType() == typeof(DateTime))
                                {
                                    var c = new DateCell(headers[col].ToString(), 
                                               (DateTime)obj, index);
                                    r.Append(c);
                                }
                                else if (obj.GetType() == typeof(decimal) || 
                                         obj.GetType() == typeof(double))
                                {
                                    var c = new FormatedNumberCell(
                                                 headers[col].ToString(), 
                                                 obj.ToString(), index);
                                    r.Append(c);
                                }
                                else
                                {
                                    long value;
                                    if (long.TryParse(obj.ToString(), out value))
                                    {
                                        var c = new NumberCell(headers[col].ToString(), 
                                                    obj.ToString(), index);
                                        r.Append(c);
                                    }
                                    else
                                    {
                                        var c = new TextCell(headers[col].ToString(), 
                                                    obj.ToString(), index);
                                        r.Append(c);
                                    }
                                }
                            }
                        }
                    }
                    sheetData.Append(r);
                }
                index++;
                Row total = new Row();
                total.RowIndex = (uint)index;
                for (int col = 0; col < numCols; col++)
                {
                    var obj1 = objects[0];
                    string fieldName = fields[col];
                    PropertyInfo myf = obj1.GetType().GetProperty(fieldName);
                    if (myf != null)
                    {
                        object obj = myf.GetValue(obj1, null);
                        if (obj != null)
                        {
                            if (col == 0)
                            {
                                var c = new TextCell(headers[col].ToString(), 
                                                     "Total", index);
                                c.StyleIndex = 10;
                                total.Append(c);
                            }
                            else if (obj.GetType() == typeof(decimal) || 
                                     obj.GetType() == typeof(double))
                            {
                                string headerCol = headers[col].ToString();
                                string firstRow = headerCol + "2";
                                string lastRow = headerCol + (numRows + 1);
                                string formula = "=SUM(" + firstRow + " : " + lastRow + ")";
                                //Console.WriteLine(formula);
                                var c = new FomulaCell(headers[col].ToString(), 
                                                       formula, index);
                                c.StyleIndex = 9;
                                total.Append(c);
                            }
                            else
                            {
                                var c = new TextCell(headers[col].ToString(), 
                                                     string.Empty, index);
                                c.StyleIndex = 10;
                                total.Append(c);
                            }
                        }
                    }
                }
                sheetData.Append(total);
            }
            return sheetData;
        }
        private static List<string> GetPropertyInfo<T>()
        {
            PropertyInfo[] propertyInfos = typeof(T).GetProperties();
            // write property names
            return propertyInfos.Select(propertyInfo => propertyInfo.Name).ToList();
        }
    }
}

如何使用该类

下面是一个如何使用该类的示例,您应该会看到 Excel 2007 电子表格。创建一个包对象列表并将对象传递到 Excel 助手类;创建一个方法以及完整路径文件名、工作表名称和标题名称列表。

编译您的项目,运行应用程序,然后惊叹不已。您刚刚创建了一个 Excel 2007 电子表格。

using System;
using System.Collections.Generic;

namespace CreateExcelSpreadsheet
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                List<package> packages =
                    new List<package>
                        { new Package { Company = "Coho Vineyard", Weight = 25.2, 
                              TrackingNumber = 89453312L, 
                              DateOrder = DateTime.Today, HasCompleted = false },
                          new Package { Company = "Lucerne Publishing", Weight = 18.7, 
                              TrackingNumber = 89112755L, 
                              DateOrder = DateTime.Today, HasCompleted = false },
                          new Package { Company = "Wingtip Toys", Weight = 6.0, 
                              TrackingNumber = 299456122L, 
                              DateOrder = DateTime.Today, HasCompleted = false },
                          new Package { Company = "Adventure Works", Weight = 33.8, 
                              TrackingNumber = 4665518773L, 
                              DateOrder =  DateTime.Today.AddDays(-4), 
                              HasCompleted = true },
                          new Package { Company = "Test Works", Weight = 35.8, 
                              TrackingNumber = 4665518774L, 
                              DateOrder =  DateTime.Today.AddDays(-2), 
                              HasCompleted = true },
                          new Package { Company = "Good Works", Weight = 48.8, 
                              TrackingNumber = 4665518775L, 
                              DateOrder =  DateTime.Today.AddDays(-1), HasCompleted = true },

                        };

                List<string> headerNames = 
                   new List<string> { "Company", 
                   "Weight", "Tracking Number", 
                   "Date Order", "Completed" };

                ExcelHelper excelFacade = new ExcelHelper();
                excelFacade.Create<package>(@"C:\temp\output1.xlsx", 
                            packages,"Packages", headerNames);

                Console.WriteLine("Completed");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.Read();
        }
    }

    public class Package
    {
        public string Company { get; set; }
        public double Weight { get; set; }
        public long TrackingNumber { get; set; }
        public DateTime DateOrder { get; set; }
        public bool HasCompleted { get; set; }
    }
}

历史

  • 2010 年 7 月 28 日:初始帖子。
  • 2010 年 7 月 30 日:更新了类的说明。
© . All rights reserved.