我有這段 C# 代碼,使用 ClosedXML 庫讀取 Excel 電子表格:
using ClosedXML.Excel;
...
var workbook = new XLWorkbook(new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite));
var ws1 = workbook.Worksheet("SHEET A");
var rows = ws1.RangeUsed().RowsUsed();
// Now we parse the first sheet for Faction Data
foreach (var row in rows)
{
int cellNum = 1;
foreach (IXLCell cell in row.Cells())
{
if( cellNum > 1 )
{
try
{
System.Console.WriteLine( Int32.Parse( cell.Value.ToString() ) );
}
catch (FormatException e)
{
System.Console.WriteLine("ERROR!!!" e);
}
}
cellNum ;
}
}
該代碼以只讀方式打開一個 Excel 電子表格,轉到選項卡“SHEET A”,然后對于每一行,讀取該行中的每個單元格。此外,請注意,在讀取 A 列中的單元格后,代碼假定它正在讀取一個整數,并執行字串到整數的資料型別轉換。假設我的 Excel 電子表格如下所示,這段代碼會很好用:
Apples Bananas Oranges Grapes
Store A 10 20 30 40
Store B 15 20 35 5
Store C 5 25 30 35
(是的,我省略了跳過讀取列名的代碼(Apples, Bananas, Oranges, Grapes)
到目前為止,一切都很好。但現在假設我想NOTES在最右邊添加一列:
Apples Bananas Oranges Grapes NOTES
Store A 10 20 30 40
Store B 15 20 35 5 Store B customers want more grapes
Store C 5 25 30 35
這會破壞我的代碼,因為代碼會嘗試將它在新列 ( "Store B customers want more grapes") 中找到的任何內容轉換為整數。不好!
那么......如何從本質上告訴我的代碼“在每一行中,將單元格資料轉換為除第一列單元格和最后一列單元格之外的整數”?我不能讓代碼在迭代時計算列數,因為將來我可能會添加更多水果列。(例如Papayas, Melons,Plums等)
我的一個想法基本上是一個技巧:在最后一個水果列和列之間插入一個空白列NOTES:
Apples Bananas Oranges Grapes (*blank*) NOTES
Store A 10 20 30 40 (*blank*)
Store B 15 20 35 5 (*blank*) Store B customers want more grapes
Store C 5 25 30 35 (*blank*)
我希望將迭代器向下發送的代碼行...
foreach (IXLCell cell in row.Cells())
...之后會看到空白單元格Grapes并得出結論該行已經結束。但這不起作用。
所以:有誰知道如何迭代除最后一個之外的一行中的每個單元格?
uj5u.com熱心網友回復:
如果您只是讓它跳過任何不是整數值的列怎么辦?
你的代碼:
foreach (var row in rows)
{
int cellNum = 1;
foreach (IXLCell cell in row.Cells())
{
if( cellNum > 1 )
{
try
{
System.Console.WriteLine( Int32.Parse( cell.Value.ToString() ) );
}
catch (FormatException e)
{
System.Console.WriteLine("ERROR!!!" e);
}
}
cellNum ;
}
}
使用Int32.TryParse它可以更改為:
foreach (var row in rows)
{
int cellNum = 1;
foreach (IXLCell cell in row.Cells())
{
// if we are actually able to parse a result int from our value
if(Int32.TryParse(cell.Value.ToString(), out int result))
{
// then we can
// perform anything you want for the value here
System.Console.WriteLine(result);
}
}
}
這應該允許您在將來插入新列,并且任何可以解釋為 an 的列int都將被評估。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/496271.html
