首页 > 技术文章 > 三种从DataTable导入到Excel

Smily-C 2014-09-30 14:50 原文

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using Excel= Microsoft.Office.Interop.Excel;//ASP.NET中Excel的命名空间
using System.Data.SqlClient;
using System.Data;

//输出方法
 

protected void Printer(DataTable dataGridView1)
        {
            //创建一个Excel应用程序对象,如果未创建成功则推出。
            Excel.Application excel1 = new Excel.Application();
            if (excel1 == null)
            {
                System.Web.HttpContext.Current.Response.Write("无法创建Excel对象,可能你的电脑未装Excel");
            }
            Excel.Workbooks workBooks1 = excel1.Workbooks;
            Excel.Workbook workBook1 = workBooks1.Add(Excel.XlWBATemplate.xlWBATWorksheet);
            Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workBook1.Worksheets[1]; //取得sheet1          

            //把DataTable的表头导入到Excel的第一行
            for (int i = 0; i < dataGridView1.Columns.Count; i++)
            {

                worksheet.Cells[1, i + 1] = dataGridView1.Columns[i].ColumnName.ToString();
            }

           //把DataTable的数据导入到Excel中(这里用的是两个for循环,当表中行,列比较少时       还 可以,但是比较多时,速度就会很慢,我电脑两万五千条用了尽量分钟)

                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                {
                    for (int j = 0; j < dataGridView1.Columns.Count; j++)
                    {
                        worksheet.Cells[i + 2, j + 1] = dataGridView1.Rows[i][ j].ToString();
                    }
                }
           
            try
            {
               //保存Excel
                workBook1.Saved = true;
                workBook1.SaveCopyAs("F:\\www.xlsx");

            }
            catch (Exception ex)
            {

                System.Web.HttpContext.Current.Response.Write("导出文件时出错,文件可能正被打开!\n" + ex.ToString());
            }
            workBook1.Close();
            excel1.Visible = true;


            if (excel1 != null)
            {
                excel1.Workbooks.Close();
                excel1.Quit();

                int generation = System.GC.GetGeneration(excel1);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(excel1);

                excel1 = null;
                System.GC.Collect(generation);
            }

        }

推荐阅读