2014-02-14 75 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(); 
      } 
     } 
    } 
} 
相關問題