C# DataSet導出Excel


//多個DataSet導出Excel文件
public static void DataSetToExcel(DataSet p_ds,string strSavePath)
{
    int l_intSheetIndex=1;//多個DataSet導出多個Excel,針對Excel文件中的第一個Sheet
    //實例化Excel對象
    Microsoft.Office.Interop.Excel.Application app=new Microsoft.Office.Interop.Excel.Application();
    //根據Excel對象新建Excel文件
    Microsoft.Office.Interop.Excel.Workbook book=app.Workbooks.Add(true);
    try
    {
        foreach(DataTable dt in p_ds.Tables)
        {
            if(dt!=null && dt.Rows.Count>0)
        {
        object missing=System.Reflection.Missing.Value;
        Microsoft.Office.Interop.Excel.Worksheet sheet;
        //判斷Excel文件是否存在Sheet
        //1.不存在就新建Sheet
        //2.存在就開啟對應Sheet
        if(book.Worksheets.Count < l_intSheetIndex)
        {
           //新建Sheet
           sheet=(Microsoft.Office.Interop.Excel.Worksheet)book.Worksheets.Add(Type.Missing,book.Worksheets[book.Worksheets.Count],1,Type.Missing);
        }
        //開啟對應Sheet
        sheet=(Microsoft.Office.Interop.Excel.Worksheet)book.Worksheets.get_Item(l_intSheetIndex);
        //設置Sheet名
        sheet.Name=dt.TableName;

        //取得區域  --取得區域的方式 1.設置整列 2.設置使用的區域
        //整列
        //Range column = ((Range)worksheet.Cells[1, 1]).EntireColumn;(選取A列;方法:先選取A1單元格,然后選取A1單元格所在的這一整列。)
        //使用的區域
        Microsoft.Office.Interop.Excel.Range l_range=sheet.Range[sheet.Cells[1,1],sheet.Cells[dt.Rows.Count+1,dt.Columns.Count]];
        //設置區域格式“@”是文本格式
        l_range.NumberFormatLocal="@";
        int i=0;
        foreach(DataColumn dc in dt.Columns)
        {
            sheet.Cells[1,i+1]=dc.ColumnName;
            i++;
        }
        int j=0;
        foreach(DataRow dr in dt.Rows)
        {
            int k=0;
            foreach(DataColumn dc in dt.Columns)
            {
            sheet.Cells[j+2,k+1]=dr[k].ToString();
            k++;
            }
        }
        book.Saveed=true;
        }
        l_intSheetIndex++;
        }
    ((Microsoft.Office.Interop.Excel.WorkSheet)book.Worksheets.get_Item(1)).Select();
    book.SaveAs(strSavePath);
    book.Close(Type.Missing,Type.Missing,Type.Missing);
    }
    catch(Exception ex)
    {
    throw ex;
    }
    finally
    {
    app.Quit();
    IntPtr t=new IntPtr(app.Hwnd);
    int d=0;
    GetWindowThreadProcessId(t,out d);
    System.Diagenostics.Process p=System.Diagnostics.Process.GetProcessById(d);
    p.Kill();
    }
}

[DllImport("User32.dll",CharSet=CharSet.Auto)]
Public static extern int GetWindowThreadProcessId(IntPtr hwnd,out int ID);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM