c# - 使用 OpenXML 将数据集转换为 Excel

标签 c# excel

我有一个数据集,上面有几个表。我想将其导出到 Excel,其中每个表将位于不同的工作表上。我如何使用 OpenXML 来做到这一点,但我想保留列的 DataType(例如:字符串、日期、数字等)?
目前我有:

using (SpreadsheetDocument workbook = SpreadsheetDocument.Create(fileName,
    SpreadsheetDocumentType.Workbook)){
workbook.AddWorkbookPart();
workbook.WorkbookPart.Workbook = new Workbook {Sheets = new Sheets()};

uint sheetId = 1;

var sheetPart = workbook.WorkbookPart.AddNewPart<WorksheetPart>();
var sheetData = new SheetData();
sheetPart.Worksheet = new Worksheet(sheetData);

var sheets = workbook.WorkbookPart.Workbook.GetFirstChild<Sheets>();
string relationshipId = workbook.WorkbookPart.GetIdOfPart(sheetPart);

if (sheets.Elements<Sheet>().Any())
{
    sheetId = sheets.Elements<Sheet>().Select(s => s.SheetId.Value).Max() + 1;
}

var sheet = new Sheet
{
    Id = relationshipId,
    SheetId = sheetId,
    Name = exportedSheet
};
sheets.Append(new List<OpenXmlElement> {sheet});

var headerRow = new Row();

var columns = new List<string>();
foreach (DataColumn column in extractedData.Columns)
{
    columns.Add(column.ColumnName);

    var cell = new Cell
    {
        DataType = CellValues.String,
        CellValue = new CellValue(column.ColumnName)
    };
    headerRow.AppendChild(cell);
}

sheetData.AppendChild(headerRow);

foreach (DataRow dsrow in extractedData.Rows)
{
    var newRow = new Row();
    DataRow dsrow1 = dsrow;
    foreach (Cell cell in columns.Select(col => new Cell
    {
        DataType = CellValues.String,
        CellValue = new CellValue(dsrow1[col].ToString())
    }))
    {
        newRow.AppendChild(cell);
    }

    sheetData.AppendChild(newRow);
}}

最佳答案

您只需要将每列的值映射到对应的CellValues值(value)。这是粗略的想法。

// store this somewhere (a static field?)
var columnTypeToCellDataTypeMap = new Dictionary<Type, CellValues>
    {
        { typeof(Boolean), CellValues.Boolean },
        { typeof(Byte), CellValues.Number },
        { typeof(Char), CellValues.String },
        { typeof(DateTime), CellValues.Date },
        { typeof(Double), CellValues.Number },
        { typeof(Decimal), CellValues.Number },
        { typeof(Int16), CellValues.Number },
        { typeof(Int32), CellValues.Number },
        { typeof(Int64), CellValues.Number },
        { typeof(SByte), CellValues.Number },
        { typeof(Single), CellValues.Number },
        { typeof(String), CellValues.String },
        { typeof(UInt16), CellValues.Number },
        { typeof(UInt32), CellValues.Number },
        { typeof(UInt64), CellValues.Number },
    }

// and use it like this:
foreach (DataRow row in table.Rows)
{
    foreach (DataColumn column in table.Columns)
    {
        // map the column type to an OpenXML SDK CellValues type
        CellValues cellDataType;
        if (!columnTypeToCellDataTypeMap.TryGetValue(column.DataType, out cellDataType))
            cellDataType = CellValues.String;

        // get the cell value
        object value = row[column];
        string cellValue = (value != null ? value.ToString() : "");

        // construct the cell
        var cell = new Cell { DataType = cellDataType, CellValue = value };

        // etc
        ...
    }
}

关于c# - 使用 OpenXML 将数据集转换为 Excel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21993964/

相关文章:

c# - 如何取消和回滚部分工作流程

c# - Selenium WebDriver (C#)。将元素拖放到 iframe 中

Excel 在行中最右边的字母数字单元格中查找值

vba - 工作表中的最大值

excel - 如果列包含日期,则 IF 语句计算日期之间的天数

php - 使用php导入excel文件而不更改为csv格式

c# - 代码优先迁移 - Entity Framework - 无法向表中添加列

c# - 从 C# 访问 C++ DLL 库

c# - 如何将以下 JSON 传递到带有或不带有 Javascript 序列化器的 C# 修补方法

excel - 如何过滤列中的非彩色单元格