(一)  导出excel表(将数据库里的数据表保存为xls的文件)

1.先得出一个表Table。
2.在代码中建一个excel实例。
   在建实例前先引用Microsoft.Office.Interop.Excel组件——添加引用
   Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
   excel.Workbooks.Add(true);
3.将table时的数据,循环遍历插入到excel中。

具体实例如下:
        string connectionstr = "Server=192.168.1.10;database=ssh;uid=sa;pwd=1234";
        string sqlstr = "select * from medstock";
        SqlConnection con = new SqlConnection(connectionstr);
        SqlCommand cmd = new SqlCommand(sqlstr,con);
        DataSet ds = new DataSet();
        DataTable db = new DataTable();
        SqlDataAdapter adp = new SqlDataAdapter(cmd);//由于SqlDataAdapter自身带有数据库打开与关闭功能,所以不用手动打开数据库与关闭。
        adp.Fill(ds,"table1");
        db = ds.Tables["table1"];

        //建列名,根据实际情况而定,即要在excel中显示的列名;
        string[] str=new string[db.Columns.Count];
        for (int i = 0; i < str.Length-2; i++)
        {
            str[i] = db.Columns[i+1].ColumnName;
        }
       //建excel实例。也就是table的容器;
       Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
       excel.Workbooks.Add(true);
       //先在excel中显示出table的列名;
       for (int i = 0; i < str.Length; i++)
       {
            excel.Cells[1, i + 1] = str[i];
       }
       //再向excel中循环添加表中的每一行的每一列;
       if (db.Rows.Count > 0)
            {
                for (int i = 0; i < db.Rows.Count; i++)
                {
                    for (int j = 1; j < db.Columns.Count; j++)
                    {
                        string str1 = db.Rows[i][j].ToString();
                        excel.Cells[i + 2, j] = "'" + str1;
                   }
                }
            }
        //设置禁止弹出保存和覆盖的询问提示框  
        // excel.DisplayAlerts = false;
        // excel.AlertBeforeOverwriting = false;
        excel.Save();//保存excel文件         
        excel.Quit();//确保Excel进程关闭
        excel.Visible = true;// 前台可见 后台运行
        excel = null;

posted on 2012-05-14 16:39 SkyDream 阅读(1349) 评论(0)  编辑  收藏 所属分类: C# WinForm

<2012年5月>
293012345
6789101112
13141516171819
20212223242526
272829303112
3456789

导航

统计

常用链接

留言簿(3)

随笔分类

随笔档案

文章分类

文章档案

搜索

最新评论

阅读排行榜

评论排行榜