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

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

命名空间:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Excel= Microsoft.Office.Interop.Excel;
using System.Reflection;
using System.Data.SqlClient;
using System.Data;

第一种方法是直接用两个For循环把数据导入到Excel中
for(int i; i)
{
    for(int j;j)
       {
           excel1.Cells[i,j]=dataTable.rows[i][j].ToString();
       }
}
这种方法适合数据量不大,表列比较少的情况。

第二种方法是用一个for循环

int colunt_num=daTable.colunt.Count;
for(int i;i)
{
   excel1.Range[excel1.Cells[i + 2, 1], excel1.Cells[i + 2, column]].Value = dataGridView1.Rows[i].ItemArray;
}
这种方法和第一种方法效率差不多。

第三种方法是在内存中建立一个二维数组,用两个for循环把数据放到这个二维数组中,然后再把这个二维数组导入到表格中,这个效率很高

            //获得表的行,列数目

             int row_num = dataTable.Rows.Count;
            int column_num = dataTable.Columns.Count;

          //生成一个二维数组

            object[,] dataArry = new object[row_num, column_num];

           //把表中的数据放到数组中 

            for (int i = 0; i < row_num; i++)
            {
                for (int j = 0; j < column_num; j++)
                {
                    dataArry[i,j] = dataTable.Rows[i][j].ToString();
                }
            }
            //把数组中的数据放到Excel中
            excel1.Range[excel1.Cells[1,1],excel1.Cells[row_num,column_num]].Value=dataArry;

推荐阅读