將DataTable中的數據導出成Excel


public bool ExportFile(System.Data.DataTable dt)
{
    SaveFileDialog sfd = new SaveFileDialog();
    sfd.Filter = "Excel文件(*.xls)|*.xls|所有文件(*.*)|*.*";
    sfd.Title = "Excel文件導出";
    string fileName = "";
    if (sfd.ShowDialog() == DialogResult.OK)
    {
        fileName = sfd.FileName;
        Excel.Application app = new Excel.Application();
        if (app == null)
        {
            MessageBox.Show("Excel啟動失敗!");
            return false;
        }
        try
        {
            app.Visible = false;
            Excel.Workbook xlWorkBook = app.Workbooks.Add(Type.Missing);
            Excel.Worksheet xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
            int i;
            for (i = 0; i < dt.Columns.Count; i++)
            {
                xlWorkSheet.Cells[1, i + 1] = dt.Columns[i].ColumnName;
            }
            for (i = 0; i < dt.Rows.Count; i++)
            {
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    string tt = dt.Rows[i][j].ToString();
                    xlWorkSheet.Cells[i + 2, j + 1] = tt;
                }
            }
            xlWorkBook.SaveAs(fileName, Excel.XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            xlWorkBook.Close(true, Type.Missing, Type.Missing);
            app.Quit();                   
                   
            xlWorkSheet = null;
            xlWorkBook = null;

            return true;
        }
        catch (System.Exception exc)
        {
            MessageBox.Show("excel運行錯誤:" + exc.Message);
            return false;
        }
    }
    else
    {
        return false;
    }
}


免責聲明!

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



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