C#导出数据到Excel的几种方法

来源:互联网 发布:网络课影视鉴赏答案 编辑:程序博客网 时间:2024/05/22 03:20

首先说明,以下几种方法都是将DataTable 中导出数据到Excel 。

1、需要加载固定的Excel模板的方式

第一步,添加简单的 SaveFileDialog,以便将文件保存到合适的位置。

SaveFileDialog SaveDialog = new SaveFileDialog();                    SaveDialog.Filter = "Excel 文件(*.xls)|*.xls|Excel 文件(*.xlsx)|*.xlsx|所有文件(*.*)|*.*";                    SaveDialog.RestoreDirectory = true;                    if (SaveDialog.ShowDialog() == DialogResult.OK)                    {                        GenerateAttachment(SaveDialog.FileName,dtExport);                    }
第二步,真正的导出部分的代码

 try            {                //需要添加 Microsoft.Office.Interop.Excel引用                 Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();                if (app == null)//服务器上缺少Excel组件,需要安装Office软件                {                    return;                }                app.Visible = false;                app.UserControl = true;                string strTempPath = System.Windows.Forms.Application.StartupPath + "\\Template\\Form.xls";                Microsoft.Office.Interop.Excel.Workbooks workbooks = app.Workbooks;                Microsoft.Office.Interop.Excel._Workbook workbook = workbooks.Add(strTempPath); //加载模板                Microsoft.Office.Interop.Excel.Sheets sheets = workbook.Sheets;                Microsoft.Office.Interop.Excel._Worksheet worksheet = (Microsoft.Office.Interop.Excel._Worksheet)sheets.get_Item(1); //第一个工作薄。                if (worksheet == null)//工作薄中没有工作表                {                    return;                }                //1、获取数据                int rowCount = DT.Rows.Count;                if (rowCount < 1)//没有取到数据                {                    return;                }                //2、写入数据,Excel索引从1开始                for (int i = 1; i <= rowCount; i++)                {                    int row_ = 1 + i;  //Excel模板上表头占了1行                    int dt_row = i - 1; //dataTable的行是从0开始的                     worksheet.Cells[row_, 1] = DT.Rows[dt_row]["itemname"].ToString();                    worksheet.Cells[row_, 2] = DT.Rows[dt_row]["Color"].ToString();                    worksheet.Cells[row_, 3] = DT.Rows[dt_row]["Grade1"].ToString();                   // worksheet.Cells[row_, 4] = DT.Rows[dt_row]["ProAreaName"].ToString();                    worksheet.Cells[row_, 4] = DT.Rows[dt_row]["Quantity"].ToString();                    worksheet.Cells[row_, 5] = DT.Rows[dt_row]["Unit_name"].ToString();                    worksheet.Cells[row_, 6] = DT.Rows[dt_row]["TotalAmt"].ToString();                                    }                worksheet.Cells[DT.Rows.Count + 2, 1] = "合计";                worksheet.Cells[DT.Rows.Count + 2, 4] = DT.Compute("sum(Quantity)", "");                worksheet.Cells[DT.Rows.Count + 2, 6] = DT.Compute("sum(TotalAmt)", "");                //调整Excel的样式。                //Microsoft.Office.Interop.Excel.Range rg = worksheet.Cells.get_Range("A3", worksheet.Cells[rowCount + 2, 32]);                //rg.Borders.LineStyle = 1; //单元格加边框                //worksheet.Columns.AutoFit(); //自动调整列宽                //隐藏某一行                //选中部分单元格,把选中的单元格所在的行的Hidden属性设为true                //worksheet.get_Range(app.Cells[2, 1], app.Cells[2, 32]).EntireRow.Hidden = true;                //删除某一行               // worksheet.get_Range(app.Cells[2, 1], app.Cells[2, 32]).EntireRow.Delete(Microsoft.Office.Interop.Excel.XlDirection.xlUp);                //3、保存生成的Excel文件                //Missing在System.Reflection命名空间下                //string savePath = System.Windows.Forms.Application.StartupPath+"/Temp/T1_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";                workbook.SaveAs(FileName, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);                //workbook.SaveAs(FileName,FileFormat,Password,WriteResPassword,ReadOnlyRecommended,CreateBackup, AccessMode, ConflictResolution, AddToMru, TextCodepage, TextVisualLayout, Local)                 //4、按顺序释放资源                NAR(worksheet);                NAR(sheets);                NAR(workbook);                NAR(workbooks);                app.Quit();                NAR(app);                MessageBox.Show("保存成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);            }            catch (Exception ex)            {               MessageBox.Show("异常,异常信息为:"+ex.ToString(),"");            }
上述代码中  workbook.SaveAs()方法没有任何问题。开发过程中遇到错误为“值不在预期范围内”,报错位置在此方法,但出错的地方在上面的方法中,有可能是模板,有可能是FileName,总之,不会是这个方法。


第二种,调入内存导出

导入部分的方法

  public static void RenderDataTableToExcel(DataTable SourceTable, string FileName)        {            MemoryStream ms = RenderDataTableToExcel(SourceTable) as MemoryStream;            FileStream fs = new FileStream(FileName, FileMode.Create, FileAccess.Write);            byte[] data = ms.ToArray();            fs.Write(data, 0, data.Length);            fs.Flush();            fs.Close();            data = null;            ms = null;            fs = null;        }
引用该方法的代码 ,其中strDataOutFile 同样可以用SaveFileDialog

 string strDataOutFile = TxtDataOutPath.Text.Trim() + TxtDataOutFileName.Text.Trim(); RenderDataTableToExcel(DT_Item, strDataOutFile);
这种方法导出的数据全都是文本格式的,导出的Excel表格种的数据不能进行计算。暂时未找到合适的解决办法。
第三种,直接导出到临时表

 protected void ExportExcel(DataTable dt)        {            if (dt == null || dt.Rows.Count == 0) return;            Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();            if (xlApp == null)            {                return;            }            System.Globalization.CultureInfo CurrentCI = System.Threading.Thread.CurrentThread.CurrentCulture;            System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");            Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;            Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);            Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];            Microsoft.Office.Interop.Excel.Range range;            long totalCount = dt.Rows.Count;            long rowRead = 0;            float percent = 0;            for (int i = 1; i < dt.Columns.Count; i++)            {                worksheet.Cells[1, i] = dt.Columns[i].ColumnName;                range = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[1, i];                range.Interior.ColorIndex = 15;                range.Font.Bold = true;            }            for (int r = 0; r < dt.Rows.Count; r++)            {                for (int i = 1; i < dt.Columns.Count; i++)                {                    worksheet.Cells[r + 2, i] = dt.Rows[r][i].ToString();                }                rowRead++;                percent = ((float)(100 * rowRead)) / totalCount;            }            worksheet.Cells[dt.Rows.Count + 2, 1] = "合计";            worksheet.Cells[dt.Rows.Count + 2, 5] = textBox2.Text;            xlApp.Visible = true;        }


    
    


         

原创粉丝点击