public static void ExportToExcel(DataTable dt, string fileName)
        {
            //在做这些前,将Excl添加到引用中来!!
            Excel.Application excel = new Excel.Application();
            //如果系统是Excl2007,添加的引用会不一样,代码如下。
            //Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
            if (excel == null)
            {
              
            }
            else
            {
                Excel.Workbook xlBook = excel.Workbooks.Add(true);
                Excel.Worksheet xlSheet = (Excel.Worksheet)xlBook.Worksheets[1];
                //excel.Application.Workbooks.Add(true);           
                int cols = dt.Columns.Count;
                int rows = dt.Rows.Count;
                //列
                for (int k = 0; k < cols; k++)
                {
                    excel.Cells[1, k + 1] = dt.Columns[k].ColumnName;
                }
                //数据
                for (int i = 0; i < rows - 1; i++)
                {
                    for (int j = 0; j < cols; j++)
                    {
                      
                            excel.Cells[i + 2, j + 1] = dt.Rows[i][j].ToString();
                    }
                }
   
                try
                {
                    xlBook.Saved = true;
                    xlBook.SaveCopyAs(fileName);
                }
                catch
                {
             
                }
          
            }
        }

http://files.cnblogs.com/wangdetian168/Interop.Excel.rar

posted on 2010-10-22 01:48 sanmao 阅读(374) 评论(0)  编辑  收藏

只有注册用户登录后才能发表评论。


网站导航:
 

常用链接

留言簿(5)

随笔分类

随笔档案

搜索

  •  

最新评论

阅读排行榜

评论排行榜