2014-02-14 47 views
0

我无法用ado.netupdate替换某些excel单元格。我无法用ado.net替换某些excel单元格并更新

在一些单元格中,我有这个字符串:='C:\#Control\#RESULT\CUENTAS 2008\,我想将此字符串更改为='T:\#Control\#RESULT\CUENTAS 2008\,但我不能。

这是我的代码,但我不知道是什么问题?

有人可以帮我吗?

namespace Leer_Excel 
{ 
    public class Class1 
    { 
     public static void Modificar_Excel(string excelFileName, string sheetName) 
     { 
      string TextoBuscado = "'C:'"; 
      string TextoDeRemplazo = "'T:'"; 

      OleDbConnection Connection = new OleDbConnection(); 

      try 
      { 
       OleDbCommand cmd = new OleDbCommand(); 

       string strConnnectionOle = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excelFileName + @";Extended Properties=" + '"' + "Excel 12.0;HDR=NO" + '"'; 
       Connection.ConnectionString = strConnnectionOle; 
       Connection.Open(); 

       string MyCommandText = "UPDATE [" + sheetName + "$B9:B9] SET F1 = REPLACE(F1," + TextoBuscado + "," + TextoDeRemplazo + ") WHERE F1 LIKE '%C:%'"; 

       Console.WriteLine(MyCommandText); 

       cmd.CommandText = MyCommandText; 
       cmd.Connection = Connection; 
       cmd.ExecuteNonQuery(); 
      } 
      catch (Exception ex) 
      { Console.WriteLine("El fichero {0} no ha podido realizar los updates correctamente {1}", excelFileName,ex.ToString()); } 
      finally 
      { Connection.Close(); } 

     } 
    } 
} 

谢谢!

+0

有什么异常的确切的错误信息? – mnieto

+0

我没有任何异常错误。我的程序工作正确,但是当我查看我的excel文件时,我没有任何更改 –

+0

嗨,我为因特网阅读,我无法更改Excel公式(以“=”开头)。我认为,这是我的问题。 –

回答

0

为什么不使用其他aproach?我已经使用EPPlus 您可以download the package from Nuget

这个例子是为我工作:

using System; 
using System.Collections.Generic; 
using OfficeOpenXml; 
using System.IO; 


namespace ConsoleApplication4 { 
    class Program { 
     static void Main(string[] args) { 
      const string buscado = "C:"; 
      const string reemplazo = "T:"; 
      const string test = "='" + buscado; 
      using (ExcelPackage xls = new ExcelPackage(new FileInfo(@"E:\Libro1.xlsx"))) { 
       ExcelWorksheet sheet = xls.Workbook.Worksheets[1]; 
       int row = 1; 
       while (sheet.Cells[row, 1].Value != null) { 
        if (sheet.Cells[row, 1].Text.Substring(0, 4) == test) { 
         sheet.Cells[row, 3].Value = sheet.Cells[row, 1].Value.ToString().Replace(buscado, reemplazo); 
        } 
        row++; 
       } 
       xls.Save(); 
      } 
     } 
    } 
} 
相关问题