【问题标题】:How I can read a cell in excel with C#?如何使用 C# 读取 excel 中的单元格?
【发布时间】:2013-04-22 16:43:01
【问题描述】:

我想用 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 automation excel-2010 cells


【解决方案1】:

我认为您应该再次查看您的代码。当您要求一个范围时,您将要读取的外壳从哪个到哪个外壳。

例如:

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

【讨论】:

    猜你喜欢
    • 2013-07-31
    • 1970-01-01
    • 1970-01-01
    • 2020-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-16
    • 2017-05-31
    相关资源
    最近更新 更多