我有一个excel单元格地址数组,我只需要将这些单元格值读取到字典中,即我需要使用open xml来执行此操作。有什么帮助吗?
当我正在阅读时,我只获得数字值,并且字符串类型的单元格会出现一些数字。或者使用openxml从excel读取多个单元格的任何特定方法?
public static Dictionary<string, string> GetCellValue(string filePath, string sheetName)
{
string[] adderssNames = { "H29", "H30", "H31", "H32", "H33", "H36", "H37", "H38", "H40", "H41", "H42", "H43", "H47",
"H48", "H49", "H50", "H51", "H52", "H57", "H58", "H61", "H62", "H65", "H66", "H69", "H70",
"I29", "I30", "I31", "I32", "I33", "I36", "I37", "I38", "I40", "I41", "I42", "I43", "I47",
"I48", "I49", "I50", "I51", "I52", "I57", "I58", "I61", "I62", "I65", "I66", "I69", "I70",
"J29", "J30", "J31", "J32", "J33", "J36", "J37", "J38", "J40", "J41", "J42", "J43", "J47",
"J48", "J49", "J50", "J51", "J52", "J57", "J58", "J61", "J62", "J65", "J66", "J69", "J70",
"K29", "K30", "K31", "K32", "K33", "K36", "K37", "K38", "K40", "K41", "K42", "K43", "K47",
"K48", "K49", "K50", "K51", "K52", "K57", "K58", "K61", "K62", "K65", "K66", "K69", "K70",
"L29", "L30", "L31", "L32", "L33", "L36", "L37", "L38", "L40", "L41", "L42", "L43", "L47",
"L48", "L49", "L50", "L51", "L52", "L57", "L58", "L61", "L62", "L65", "L66", "L69", "L70",
};
Dictionary<string, string> cellValues = new Dictionary<string, string>();
string value = null;
using (SpreadsheetDocument document = SpreadsheetDocument.Open(filePath, false))
{
WorkbookPart wbPart = document.WorkbookPart;
Sheet theSheet = wbPart.Workbook.Descendants<Sheet>().
Where(s => s.Name == sheetName).FirstOrDefault();
if (theSheet == null)
{
throw new ArgumentException("Invalid sheet name");
}
WorksheetPart wsPart =
(WorksheetPart)(wbPart.GetPartById(theSheet.Id));
for (int i = 0; i < adderssNames.Length; i++)
{
Cell theCell = wsPart.Worksheet.Descendants<Cell>().
Where(c => c.CellReference == adderssNames[i]).FirstOrDefault();
if (theCell != null)
{
value = theCell.CellValue == null ? "" : theCell.CellValue.Text;
cellValues.Add(adderssNames[i], value);
if (theCell.DataType != null)
{
switch (theCell.DataType.Value)
{
case CellValues.SharedString:
var stringTable =
wbPart.GetPartsOfType<SharedStringTablePart>()
.FirstOrDefault();
if (stringTable != null)
{
value =
stringTable.SharedStringTable
.ElementAt(int.Parse(value)).InnerText;
}
break;
case CellValues.Boolean:
switch (value)
{
case "0":
cellValues[adderssNames[i]] = "FALSE";
break;
default:
cellValues[adderssNames[i]] = "TRUE";
break;
}
break;
}
}
}
}
}
return cellValues;
}
由于 Ragesh