Using OpenXML to insert a datatable into excel

前端 未结 1 592
闹比i
闹比i 2021-01-15 17:11

I have a datatable that - depending on the user selection - will generate a dynamic datatable with any number of rows and columns. I\'m currently using OpenXml to manipulate

相关标签:
1条回答
  • 2021-01-15 17:48

    I found some code which I was able to modify to suit my needs. Hope someone finds this useful.

            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;
        }
    
    0 讨论(0)
提交回复
热议问题