将所有数据从数据表导出到excel以使用C#下载它的最佳和最简单的方法?

问题描述 投票:0回答:1

使用C#,这是将数据表中的所有数据导出到excel以下载它的最佳和最简单的方法吗?

datatable excel-interop
1个回答
0
投票

我使用Microsoft Interop。

这里有一些示例代码可以帮助您入门。

可能有数百个教程比下面的更好。我已经删除了我使用的大部分代码,因此我怀疑以下内容是否会编译,但仔细阅读并对教程进行一些调查后,您应该能够完成所需的操作。

public static void ExportToExcel(DataSet dsTodo, string strPathToSaveFile)
{
    try
    {
        int numSteps = (dsTodo != null ? dsTodo.Tables.Count * 2 : 1);

        Microsoft.Office.Interop.Excel.ApplicationClass ExcelApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
        Workbook xlWorkbook = ExcelApp.Workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);


        if (dsTodo.Tables.Count > 0)
        {
             for (int i = dsTodo.Tables.Count; i > 0; i--)
            {
                Sheets xlSheets = null;
                Worksheet xlWorksheet = null;
                //Create Excel Sheets
                xlSheets = ExcelApp.Sheets;
                xlWorksheet = (Worksheet)xlSheets.Add(xlSheets[1], Type.Missing, Type.Missing, Type.Missing);

                System.Data.DataTable table = dsTodo.Tables[i - 1];
                xlWorksheet.Name = table.TableName;

                for (int j = 1; j < table.Columns.Count + 1; j++)
                {
                    ExcelApp.Cells[1, j] = table.Columns[j - 1].ColumnName;
                }

                var excelData = new object[table.Rows.Count, table.Columns.Count];
                for (int rowJ = 0; rowJ < table.Rows.Count; rowJ++)
                {
                    for (int colI = 0; colI < table.Columns.Count; colI++)
                    {
                        excelData[rowJ, colI] = table.Rows[rowJ][colI];
                    }
                }

                int startCol = 1;
                int endCol = startCol + table.Columns.Count - 1;
                int startRow = 2;
                int endRow = startRow + table.Rows.Count - 1;
                string startLoc = GetCellFromCoords(startCol, startRow);
                string endLoc = GetCellFromCoords(endCol, endRow);
                //ExcelApp.get_Range(startLoc, endLoc).Value2 = excelData;
                try
                {
                    Range valRange = ExcelApp.get_Range(startLoc, endLoc);
                    valRange.Value2 = excelData;
                }
© www.soinside.com 2019 - 2024. All rights reserved.