将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;
    }
}

你可能感兴趣的:(Datatable)