0

经过一些测试,似乎很少有问题。

此代码现在正在复制文件..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();
            }
        }
    }
4

1 回答 1

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 命名空间中的对象、类、枚举和接口。如果没有该行,您应该在每个类(如 File)前加上其完全限定的命名空间

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

如您所见,打字不太方便。

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

你有一些选择:

  • 将完全限定的文件名传递给任意目录(即“C:\MyFiles\destinationFile.xls”)。
  • 在配置文件中定义一个路径,并将此路径添加到传入的文件名中。
  • 在您的配置文件中定义一个相对路径,并写入一个相对于已知路径(如 MyDocuments)的目录
于 2012-08-13T09:33:22.730 回答