[英]C#, how to update particular Cell in an Excel file
我在 C# 中创建了一个 windows 应用程序,我正在使用 excel 作为临时数据库。 我能够读取 excel 数据,但我不知道如何使用 C# 更新该文件中的单元格值。
结构如下:
我想在完成执行后将 done 字段更新为yes
。
如果您使用excel作为OLEDB数据源,那么您将使用SQL,就像它是一个数据库一样。 查询看起来有点像:
SELECT [Column Name One], [Column Name Two] FROM [Sheet One$]
在你的情况下
UPDATE [Sheet One$]
SET [column1]=value, [done]='yes'
WHERE [some_column]=some_value
如果你需要更多的帮助环顾四周,有很多关于此的信息。 也许http://www.codeproject.com/Articles/8500/Reading-and-Writing-Excel-using-OLEDB将帮助您入门。
我必须更新
Extended Properties=HDR=NO; IMEX=1
同
Extended Properties=HDR=YES;
所以它将是:
connString = "Provider=Microsoft.Jet.OLEDB.4.0;Excel 8.0; Extended Properties=HDR=YES;Data Source=" + Directory.GetCurrentDirectory() + "/swtlist.xls";
OleDbConnection oledbConn = new OleDbConnection(connString);
oledbConn.Open();
DataTable dt = oledbConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
OleDbCommand cmd = new OleDbCommand("UPDATE [Sheet1$] SET done='yes' where id=1", oledbConn);
cmd.ExecuteNonQuery();
要使用 C# 更新 excel,您只需获取工作表 object,然后使用单元格地址 (xlWorksheet.Cells[1,1]) 使用该更新单元格。 请参阅下面的示例代码。
using System;
using Excel = Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;
namespace ConsoleApplication {
public class Program {
public string[,] someImportantData;
public string[,] ExtractData(string path) {
try {
// Excel Instance declartion
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(path);
Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1]; // Insert your sheet index here
Excel.Range xlRange = xlWorksheet.UsedRange;
// Some code goes here
// Update the excel worksheet
xlWorksheet.Cells[1, 1] = 4;
xlWorksheet.Cells[1, 2] = "Value";
xlApp.Workbooks.Close();
xlApp.Quit();
Marshal.ReleaseComObject(xlWorksheet);
Marshal.ReleaseComObject(xlWorkbook);
Marshal.ReleaseComObject(xlApp);
return someImportantData;
}
catch (Exception Ex) {
throw Ex;
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.