[英]Read column index and column value from an excel in c#
我有一個ac#應用程序,可以從excel文件中讀取數據。
我用了
Range xlRng = (Range)workSheet.get_Range("A1:B6", Missing.Value);
從A1到B6單元讀取值
如果我給定范圍,則需要讀取字典中的值,並且鍵名必須是單元格索引,並且值必須是對應的單元格值
核心價值
A1值1
B1值2
A2價值3
B2值4
您也可以嘗試
Excel.Range xlRng = (Excel.Range)workSheet.get_Range("A1:B6", Type.Missing);
Dictionary<string, string> dic = new Dictionary<string, string>();
foreach (Excel.Range cell in xlRng)
{
string cellIndex = cell.get_AddressLocal(false, false, Excel.XlReferenceStyle.xlA1, Type.Missing, Type.Missing);
string cellValue = Convert.ToString(cell.Value2);
dic.Add(cellIndex, cellValue);
}
如果您要使用與我相同的Excel名稱空間,請不要忘記導入名稱空間
using Excel = Microsoft.Office.Interop.Excel;
我希望這會有所幫助
您是否嘗試過EPPlus ?
以下是示例代碼,可以滿足您的要求:
void Main()
{
var existingFile = new FileInfo(@"c:\temp\book1.xlsx");
// Open and read the XlSX file.
using (var package = new ExcelPackage(existingFile))
{
// Get the work book in the file
ExcelWorkbook workBook = package.Workbook;
if (workBook != null)
{
if (workBook.Worksheets.Count > 0)
{
// Get the first worksheet
ExcelWorksheet sheet = workBook.Worksheets.First();
// read some data
Dictionary<string,double> cells = (from cell in sheet.Cells["A1:B6"]
where cell.Start.Column == 1
select sheet.Cells[cell.Start.Row,cell.Start.Column,cell.Start.Row,2].Value)
.Cast<object[,]>()
.ToDictionary (k => k[0,0] as string, v => (double)(v[0,1]));
//do what you need to do with the dictionary here....!
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.