打开一个Excel模板文件填充数据另存为一个文件

最近做的东西要求打开一个Excel文件模板后填充数据
开始用OleDb连接该Excel文件更新老是出错误 “需要一个可更新的.....“
http://expert.csdn.net/Expert/topic/2992/2992809.xml?temp=.4825403
如果是access这个错误多半是权限引起的 可是我做的是winform 权限是admin啊
未果
后来用ODBC测试了几个字段 都成功了
开始写程序 后发现就有那么2个单元格不听话 提示参数错误
郁闷
http://expert.csdn.net/Expert/topic/3000/3000113.xml?temp=.3331262
仍未果
没办法翻google
获得
http://www.c-sharpcorner.com/winforms/ExcelReadMG.asp
用com组件,可行哦,今早上csdn就有网友pm我问是如何搞定的
那就写到这里,
以下是部分代码,使用前要先按上文中的说明添加Com引用
...........
string strFileName = Environment.CurrentDirectory+@"\template\template.tpl";
    string strSaveFileName =
Environment.CurrentDirectory+@"\excel\"+System.DateTime.Now.ToString().Replace(":","").Replace("-","").Replace(" ","")+@".xls";
    Excel.Application ThisApplication = new Excel.ApplicationClass();
    Excel.Workbook ThisWorkBook;
    object missing = System.Reflection.Missing.Value;
    try
    { 
     //加载Excel模板文件
     ThisWorkBook = ThisApplication.Workbooks.Open(strFileName,missing,missing,missing,missing,missing,missing,missing,missing,missing,missing,missing,missing);
     Excel.Worksheet ThisSheet = (Excel.Worksheet)ThisWorkBook.Sheets[1];
     ThisSheet.Cells[7,1] = dtEnd.ToShortDateString();
     progressBar.Value = 30;
     ThisApplication.Visible = false;
     DataRow dr = dt.Rows[0];
     for( int i=0; i     {
      ThisSheet.Cells[7,i+2] = dr[i].ToString();
      progressBar.Value +=1;
     }
     //更新数据后另存为新文件
     ThisSheet.SaveAs(strSaveFileName,missing,missing,missing,missing,missing,missing,missing,missing);
    }
    catch{}
    finally
    {
     ThisApplication.Quit();
     ThisWorkBook = null;
     ThisApplication = null;
     //dt = null;
    }
    try
    { //打开刚才生成的Excel文件
     Excel.Workbook NewWorkBook;
     NewWorkBook = NewApplication.Workbooks.Open(strSaveFileName,missing,missing,missing,missing,missing,missing,missing,missing,missing,missing,missing,missing);
     Excel.Worksheet NewSheet = (Excel.Worksheet)NewWorkBook.Sheets[1];
     NewApplication.Visible = true;

//也可以使用System.Diagnostics.Process.Start(strSaveFileName);来打开新文件

    }

打开Excel后进程内会多出一个excel进程
需要手工清理
参考这片文章

http://www.eggheadcafe.com/articles/20021012.asp

http://www.aspxboy.com/476/archive.aspx

posted on 2004-04-27 08:50  活靶子.Net  阅读(16093)  评论(5编辑  收藏  举报

导航