我如何用c#在excel中读取单元格

本文关键字:读取 单元格 excel 何用 | 更新日期: 2023-09-27 18:10:21

我想用c#制作一个excel工具。该工具必须打开文件夹中的每个excel文档,并在单元格E1中查找值。如果单元格包含我搜索的值,它将被删除,文档将保存。然后应用程序将转到下一个excel文件。

我可以打开文档,但我不能在单元格中查找值。

下面是我的代码:

using Microsoft.Office.Interop.Excel;
//Preparing the required items
Microsoft.Office.Interop.Excel.Application excel = null;
Workbook wb = null;
//Start Excel 
excel = new Microsoft.Office.Interop.Excel.Application();
excel.Visible = false;
try
{
    //Open file
    wb = excel.Workbooks.Open(
        @"C:'Users'....",
        ExcelKonstanten.UpdateLinks.DontUpdate,
        ExcelKonstanten.ReadOnly,
        ExcelKonstanten.Format.Nothing,
        "", //Password
        "", //WriteResPasswort
        ExcelKonstanten.IgnoreReadOnlyRecommended,
        XlPlatform.xlWindows,
        "", //Separator
        ExcelKonstanten.Editable,
        ExcelKonstanten.DontNotifiy,
        ExcelKonstanten.Converter.Default,
        ExcelKonstanten.DontAddToMru,
        ExcelKonstanten.Local,
        ExcelKonstanten.CorruptLoad.NormalLoad);
    //Read sheets
    Sheets sheets = wb.Worksheets;
    //Select a sheet…
    Worksheet ws = (Worksheet)sheets.get_Item("Tabelle1");
    //…or a cell
    Range range = (Range)ws.get_Range("E", "1");
    //Read out the value
    string zellwert = range.Value2.ToString(); // <--- This is where I get the error!
    string zellwert = range.Value2; 
    Console.WriteLine(zellwert);
}
catch (Exception e)
{
    Console.WriteLine(e.Message);
}
finally
{
    wb.Close(false, null, null);
    excel.Quit();
}
Console.WriteLine("Prüfung abgeschlossen...");

我在这一页尝试了同样的事情:

http://blog.stefan-macke.com/2006/06/28/c-projekt-zugriff-auf-excel-dateien/

我如何用c#在excel中读取单元格

我想你应该再看看你的代码。当您请求一个范围时,您可以将从哪个shell读取到哪个shell。

例如:

Range range = ( Range ) ws. get_Range ( "E1" , "E1" ) ;