簡體   English   中英

我如何用C#讀取excel中的單元格?

[英]How I can read a cell in excel with C#?

我想在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/

我覺得你應該再看看你的代碼了。 當你要求一個范圍時,你要從哪個外殼中讀取。

例如:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM