2012-08-13 34 views
0

经过一些测试,似乎有几个问题。C#保存Excel AsCopy

此代码现在正在复制该文件。在File.Copy操作之后,有代码应该更新某些单元格,当尝试更新时,系统会因为一个错误而失败,建议它找不到该特定单元格A28 。

将代码还原为简单覆盖原始代码时,它会找到单元格A28并更新值,而不会出现问题。

任何想法?

守则是站(与覆盖原始模板):

// Declaration of variables 
ClientName = txtClientName.Text; 

string newFileName = ClientName + ".xls"; 

string Filename = "C:\\Template.xls"; 

//File.Copy(Filename, @"C:\\" + newFileName, true); 


// If you are using xls format (2003), use this connection string. 

string ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Filename + ";Extended Properties=\"Excel 8.0;HDR=NO;\""; 

string SQL1 = "UPDATE [Cover Sheet$A28:A28] SET F1='" + ClientName + "'"; 

using (OleDbConnection Connection = new OleDbConnection(ConnectionString)) 
     { 
      Connection.Open(); 
      using (OleDbCommand cmd1 = new OleDbCommand(SQL1, Connection)) 
      { 
       cmd1.ExecuteNonQuery(); 
      } 
     } 
    } 

回答

0

传递给你的程序所需的新文件名的名称,复制的模板和工作的新文件。

public void MapToExcelDocument(string newFileName) 
{ 
    // Declaration of variables 
    string templateName = "C:\\Template.xls"; 
    File.Copy(templateName, newFileName, true); 

    // If you are using xls format (2003), use this connection string.    
    string ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + 
           newFileName + ";Extended Properties=\"Excel 8.0;HDR=NO;\""; 

.... 

这种变化(呼叫File.Copy)要求该行的源代码文件的开头加入:

using System.IO; 

这句简单的话告诉编译器所使用的对象,类,System.IO名称空间中的枚举和接口。没有线,你应该每天前缀像类文件,它的完全限定的命名空间

System.IO.FileCopy(templateName, newFileName, true); 

不是很打字,你可以看到方便。

编辑:按照下面的评论我会添加另一个提示。
如果传递一个没有路径的简单文件名,File.Copy将在当前工作目录中创建新文件。当前工作目录当您在Visual Studio中工作时是bin/debugbim/release。在部署应用程序时,当前工作目录将成为应用程序启动的目录。

你有一些选择:

  • 传递一个完全合格的文件名到任意目录(即 “C:\ MYFILES \ destinationFile.xls”)。
  • 定义的路径您的配置文件中,该路径添加到 文件名中传递。
  • 在你的配置文件中定义的相对路径和相对一个 目录写入一个众所周知的路径(如我的文档)
+0

感谢您的建议,但编译器不喜欢'文件':名称文件在当前上下文中不存在。 – user1594770 2012-08-13 10:02:40

+0

在源代码的开头添加'using System.IO;'。 – Steve 2012-08-13 10:04:52

+0

添加了上面的行。没有编译器问题,但是新文件没有被创建。 – user1594770 2012-08-13 10:24:16