asp.net - 使用 OpenXML 将数据表插入 Excel

标签 asp.net openxml

我有一个数据表 - 根据用户的选择 - 将生成具有任意数量的行和列的动态数据表。我目前正在使用 OpenXml 来操作所述电子表格。我将如何插入数据表?

谢谢

斯图

最佳答案

我发现了一些代码,我可以对其进行修改以满足我的需要。希望有人觉得这很有用。

        public void ExportDataTable(System.Data.DataTable exportData, SheetData sheetData)
    {
            //add column names to the first row  
            Row header = new Row();
            header.RowIndex = (UInt32)42;
            SheetData sheetData2 = new SheetData();

            foreach (DataColumn column in exportData.Columns)
            {
                Cell headerCell = createTextCell(exportData.Columns.IndexOf(column) + 1, Convert.ToInt32(header.RowIndex.Value), column.ColumnName);
                header.AppendChild(headerCell); 
            }

            sheetData.AppendChild(header);

            //loop through each data row  
            DataRow contentRow;
            int startRow = 43;
            for (int i = 0; i < exportData.Rows.Count; i++)
            {
                contentRow = exportData.Rows[i];
                sheetData.AppendChild(createContentRow(contentRow, i + startRow));
            }

        }                    


    private Cell createTextCell(int columnIndex, int rowIndex, object cellValue)
    {
        Cell cell = new Cell();

        cell.DataType = CellValues.InlineString;
        cell.CellReference = getColumnName(columnIndex) + rowIndex;

        InlineString inlineString = new InlineString();
        Text t = new Text();

        t.Text = cellValue.ToString();
        inlineString.AppendChild(t);
        cell.AppendChild(inlineString);

        return cell;
    }

    private Row createContentRow(DataRow dataRow, int rowIndex)
    {

        Row row = new Row
        {
            RowIndex = (UInt32)rowIndex
        };

        for (int i = 0; i < dataRow.Table.Columns.Count; i++)
        {
            Cell dataCell = createTextCell(i + 1, rowIndex, dataRow[i]);
            row.AppendChild(dataCell);                
        }

        return row;
    }


    private string getColumnName(int columnIndex)
    {
        int dividend = columnIndex;
        string columnName = String.Empty;
        int modifier;

        while (dividend > 0)
        {
            modifier = (dividend - 1) % 26;
            columnName = Convert.ToChar(65 + modifier).ToString() + columnName;
            dividend = (int)((dividend - modifier) / 26);
        }

        return columnName;
    }

关于asp.net - 使用 OpenXML 将数据表插入 Excel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6072456/

相关文章:

c# - Excel共享公式展开

c# - 使用open xml和C#将图像插入到word文档中

c# - Asp.Net本地化webservice方法中的文本

c# - 禁用背景滚动

asp.net - 删除字符串中的双换行符

c# - ASP.NET Core 2.0 : Why doesn't services. AddDbContext 接受一个接口(interface)?

asp.net - 如何使用 asp.net 将 .docx 转换为 html?

c# - OOXML SDK非法字符替换

php - 使用phpword将html转换为word

c# - 必须单击两次才能在 ASP.NET 中展开 DropDownList