使用OpenXML将数据表插入excel

时间:2011-05-20 13:16:41

标签: asp.net openxml

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

由于

斯图

1 个答案:

答案 0 :(得分:3)

我找到了一些我能够修改以满足我需要的代码。希望有人觉得这很有用。

        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;
    }