簡體   English   中英

如何將多個數據集導出到 excel 表

[英]How can i export multiple dataset to an excel sheet

大家好,我想將數據dataset的數據導出到excel表。 我的dataset由 2 個Tables組成,所以我如何在單個 excel 表中寫入多個數據集值

在你必須創造之前
1.使用Excel = Microsoft.Office.Interop.Excel;//在header中,並添加正確的引用
2.Excel.Application excelHandle1 = PrepareForExport(Ds); //在調用function時添加句柄 excelHandle1.Visible = true;

 public Excel.Application PrepareForExport(System.Data.DataSet ds,string[] sheet)
    {
            object missing = System.Reflection.Missing.Value;
            Excel.Application excel = new Excel.Application();
            Excel.Workbook workbook = excel.Workbooks.Add(missing);

            DataTable dt1 = new DataTable();
            dt1 = ds.Tables[0];
            DataTable dt2 = new DataTable();
            dt2 = ds.Tables[1];


            Excel.Worksheet newWorksheet;
            newWorksheet = (Excel.Worksheet)excel.Worksheets.Add(missing, missing, missing, missing);
            newWorksheet.Name ="Name of data sheet";

//  for first datatable dt1..

            int iCol1 = 0;
            foreach (DataColumn c in dt1.Columns)
            {
                iCol1++;
                excel.Cells[1, iCol1] = c.ColumnName;
            }

            int iRow1 = 0;
            foreach (DataRow r in dt1.Rows)
            {
                iRow1++;

                for (int i = 1; i < dt1.Columns.Count + 1; i++)
                {

                    if (iRow1 == 1)
                    {
                        // Add the header the first time through 
                        excel.Cells[iRow1, i] = dt1.Columns[i - 1].ColumnName;
                    }

                    excel.Cells[iRow1 + 1, i] = r[i - 1].ToString();
                }

            }

   //  for  second datatable dt2..

            int iCol2 = 0;
            foreach (DataColumn c in dt2.Columns)
            {
                iCol2++;
                excel.Cells[1, iCol] = c.ColumnName;
            }


            int iRow2 = 0;
            foreach (DataRow r in dt2.Rows)
            {
                iRow2++;

                for (int i = 1; i < dt2.Columns.Count + 1; i++)
                {

                    if (iRow2 == 1)
                    {
                        // Add the header the first time through 
                        excel.Cells[iRow2, i] = dt2.Columns[i - 1].ColumnName;
                    }

                    excel.Cells[iRow2 + 1, i] = r[i - 1].ToString();
                }

            }




        return excel;
    }

我正在使用此代碼

而不是單個 Excel 表,您可以在每個表中寫入一個表值,

http://csharp.net-informations.com/excel/csharp-excel-export.htm

增加工作表計數,您可以將多個數據集值保存在單個 excel 文件中。

希望對您有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM