码迷,mamicode.com
首页 > 其他好文 > 详细

三种从DataTable导入到Excel

时间:2014-09-30 17:12:39      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:datagridview   http   io   os   ar   for   文件   数据   sp   

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

        }

三种从DataTable导入到Excel

标签:datagridview   http   io   os   ar   for   文件   数据   sp   

原文地址:http://www.cnblogs.com/Smily-C/p/4001973.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!