[英]Find and replace value in Excel using C#
如何从单元格中找到一些值并在Excel中替换为新值?
我尝试了这个,但是没有用:
Microsoft.Office.Interop.Excel.Application xlapp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook wb =default(Microsoft.Office.Interop.Excel.Workbook);
wb = xlapp.Workbooks.Open(FileName.ToString());
wb.Worksheets[0].Cells.Replace("find","replace");
您要做的就是更换
wb.Worksheets[0].Cells.Replace("find","replace");
与
wb.Worksheets[1].Cells.Replace("find","replace");
我建议您使用NPOI ,它可以通过Codeplex或直接通过Visual Studio中的Nuget进行访问。 它使您能够轻松地在.NET中上载,编辑和创建电子表格
上传电子表格的示例:
HSSFWorkbook hssfworkbook;
void InitializeWorkbook(string path)
{
//read the template via FileStream, it is suggested to use FileAccess.Read to prevent file lock.
//book1.xls is an Excel-2007-generated file, so some new unknown BIFF records are added.
using (FileStream file = new FileStream(path, FileMode.Open, FileAccess.Read))
{
hssfworkbook = new HSSFWorkbook(file);
}
}
然后,您可以使用电子表格的IRow和ICell集合来查找和编辑导出前所需的数据。
可以在这里找到更多示例
如果有兴趣,可以使用GemBox.Spreadsheet来实现,如下所示:
SpreadsheetInfo.SetLicense("FREE-LIMITED-KEY");
// Load your XLS, XLSX, ODS or CSV file.
ExcelFile wb = ExcelFile.Load(FileName.ToString());
ExcelWorksheet ws = wb.Worksheets[0];
// Replace all "find" occurances with "replace" text.
int row, column;
while(ws.Cells.FindText("find", out row, out column))
ws.Cells[row, column].ReplaceText("find", "replace");
// Save your XLS, XLSX, ODS or CSV file.
wb.Save(FileName.ToString());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.