WinForm中导出Excel(动态导出列)

主要代码:
            Excel.Application app = new Excel.ApplicationClass();
            app.Visible 
= false;
            afterTime 
= DateTime.Now;
            
string workbookPath = System.Windows.Forms.Application.StartupPath + "//Excel//对账明细表.xls";
            
//打开模板文件,得到WorkBook对象
            Excel.Workbook workBook = app.Workbooks.Open(workbookPath, new object[] { 3 }, new object[] { false }, new object[] { 5 },new object[] { "" }, new object[] { "" }, new object[] { false }, Excel.XlPlatform.xlWindows, nullnew object[] { false }, new object[] { true }, Excel.XlFileFormat.xlExcel9795, new object[] { true }, Missing.Value, Missing.Value);
            
if (workBook == null)
            {
                
throw new Exception("请确定是否已经有此Excel模板文件!");
            }

            Excel.Worksheet workSheet 
= (Excel.Worksheet)workBook.Sheets.get_Item(1);
            
//找模板字段
              Excel.Range range = (Excel.Range)workSheet.Rows[7, Missing.Value];
            List
<string> excelColName = new List<string>();
            List
<string> excelChargeColName = new List<string>();
            
for (int j = 2; j < 55; j++)
            {
                range 
= (Excel.Range)workSheet.Cells[6, j];
                    
                
if (range.Text.ToString().IndexOf(']'>= 0 || range.Text.ToString().IndexOf('$'>= 0)
                {
                     
string name = range.Text.ToString().Substring(1, range.Text.ToString().Length - 2);
                     excelColName.Add(name);     
//此处List集合增加需要显示列的列名             
                }
                
if (range.Text.ToString().IndexOf('$'>= 0)
                {
                     
string name = range.Text.ToString().Substring(1, range.Text.ToString().Length - 2);
                     excelChargeColName.Add(name);
//此处List集合增加需要显示的费用列列名
                }
            }

然后找数据源,可以通过存储过程取得一个数据源:假设已经得到数据源DataTabe dtNow;

 

中间的业务代码

再接下来就是批量填充到Excel中:

 

填充到Excel中

再把Excel保存:

 

保存Excel和结束Excel进程

 

以上会引用到:
using System.Diagnostics;
using Excel;
using System.Reflection;

Excel模板中: [列的名称],$费用名称$

posted @ 2009-04-16 10:50  goldkevin  阅读(1841)  评论(0)    收藏  举报