将多个gridview或数据集导出到单个或多个Excel工作表

时间:2014-02-13 04:13:11

标签: c# excel gridview xls worksheet

我正在使用此方法将单个网格导出为ex​​cel

savedialog.Filter = "Microsoft Excel Documents|*.xls";
            savedialog.DefaultExt = "xls";
            savedialog.FileName = "Document";
            if (savedialog.ShowDialog() == DialogResult.OK)
            {                    
                dtTable.ExportToXls(savedialog.FileName, true);
            }

我需要将4个gridview导出到单个Excel工作表或多个工作表

请帮我解决一下

3 个答案:

答案 0 :(得分:2)

您也可以使用它。此函数传递要导出的数据表和文件路径

public void CreateCSVFile(ref DataTable dt, string strFilePath)
            {            
                try
                {
                    // Create the CSV file to which grid data will be exported.
                    StreamWriter sw = new StreamWriter(strFilePath, false);
                    // First we will write the headers.
                    //DataTable dt = m_dsProducts.Tables[0];
                    int iColCount = dt.Columns.Count;
                    for (int i = 0; i < iColCount; i++)
                    {
                        sw.Write(dt.Columns[i]);
                        if (i < iColCount - 1)
                        {
                            sw.Write(",");
                        }
                    }
                    sw.Write(sw.NewLine);

                    // Now write all the rows.

                    foreach (DataRow dr in dt.Rows)
                    {
                        for (int i = 0; i < iColCount; i++)
                        {
                            if (!Convert.IsDBNull(dr[i]))
                            {
                                sw.Write(dr[i].ToString());
                            }
                            if (i < iColCount - 1)
                            {
                                sw.Write(",");
                            }
                        }

                        sw.Write(sw.NewLine);
                    }
                    sw.Close();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }

答案 1 :(得分:1)

您也可以从直接表创建它.. 可以按如下方式调用此扩展方法:

using System;
using System.Collections.Generic;
using System.Linq;
using Excel = Microsoft.Office.Interop.Excel;
using System.Data;
using System.Data.OleDb;

DataTable dt;
// fill table data in dt here 
...

// export DataTable to excel
// save excel file without ever making it visible if filepath is given
// don't save excel file, just make it visible if no filepath is given
dt.ExportToExcel(ExcelFilePath);

DataTable类的扩展方法:

public static class My_DataTable_Extensions
{

    // Export DataTable into an excel file with field names in the header line
    // - Save excel file without ever making it visible if filepath is given
    // - Don't save excel file, just make it visible if no filepath is given
    public static void ExportToExcel(this DataTable Tbl, string ExcelFilePath = null)
    {
        try
        {
            if (Tbl == null || Tbl.Columns.Count == 0)
                throw new Exception("ExportToExcel: Null or empty input table!\n");

            // load excel, and create a new workbook
            Excel.Application excelApp = new Excel.Application();
            excelApp.Workbooks.Add();

            // single worksheet
            Excel._Worksheet workSheet = excelApp.ActiveSheet;

            // column headings
            for (int i = 0; i < Tbl.Columns.Count; i++)
            {
                workSheet.Cells[1, (i+1)] = Tbl.Columns[i].ColumnName;
            }

            // rows
            for (int i = 0; i < Tbl.Rows.Count; i++)
            {
                // to do: format datetime values before printing
                for (int j = 0; j < Tbl.Columns.Count; j++)
                {
                    workSheet.Cells[(i + 2), (j + 1)] = Tbl.Rows[i][j];
                }
            }

            // check fielpath
            if (ExcelFilePath != null && ExcelFilePath != "")
            {
                try
                {
                    workSheet.SaveAs(ExcelFilePath);
                    excelApp.Quit();
                    MessageBox.Show("Excel file saved!");
                }
                catch (Exception ex)
                {
                    throw new Exception("ExportToExcel: Excel file could not be saved! Check filepath.\n"
                        + ex.Message);
                }
            }
            else    // no filepath is given
            {
                excelApp.Visible = true;
            }
        }
        catch(Exception ex)
        {
            throw new Exception("ExportToExcel: \n" + ex.Message);
        }
    }
}

答案 2 :(得分:0)

您必须使用Microsoft.Office.Interop.Excel来获取完整的功能,才能将内容从多个DataGridView导出到Excel。这是一篇很好的文章解释了如何做到这一点。

http://www.codeproject.com/Articles/335589/Export-Multiple-Datasets-to-Multiple-Excel-sheets