我正在使用Open XML SDK打开Excel xlsx文件,并尝试读取每个工作表中位置A1的单元格值.我使用以下代码:
using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(openFileDialog1.FileName, false))
{
var sheets = spreadsheetDocument.WorkbookPart.Workbook.Descendants<Sheet>();
foreach (Sheet sheet in sheets)
{
WorksheetPart worksheetPart = (WorksheetPart)spreadsheetDocument.WorkbookPart.GetPartById(sheet.Id);
Worksheet worksheet = worksheetPart.Worksheet;
Cell cell = GetCell(worksheet, "A", 1);
Console.Writeline(cell.CellValue.Text);
}
}
private static Cell GetCell(Worksheet worksheet, string columnName, uint rowIndex)
{
Row row = GetRow(worksheet, rowIndex);
if (row == null)
return null;
return row.Elements<Cell>().Where(c => string.Compare
(c.CellReference.Value, columnName +
rowIndex, true) == 0).First();
}
// Given a worksheet and a row index, return …Run Code Online (Sandbox Code Playgroud) 我在这里使用公认的解决方案将excel表转换为数据表.如果我有"完美"数据,这可以正常工作,但如果我的数据中间有一个空白单元格,那么它似乎会在每列中放入错误的数据.
我想这是因为在下面的代码中:
row.Descendants<Cell>().Count()
Run Code Online (Sandbox Code Playgroud)
是填充单元格的数量(不是所有列)AND:
GetCellValue(spreadSheetDocument, row.Descendants<Cell>().ElementAt(i));
Run Code Online (Sandbox Code Playgroud)
似乎找到下一个填充的单元格(不一定是该索引中的内容)所以如果第一列为空并且我调用ElementAt(0),它将返回第二列中的值.
这是完整的解析代码.
DataRow tempRow = dt.NewRow();
for (int i = 0; i < row.Descendants<Cell>().Count(); i++)
{
tempRow[i] = GetCellValue(spreadSheetDocument, row.Descendants<Cell>().ElementAt(i));
if (tempRow[i].ToString().IndexOf("Latency issues in") > -1)
{
Console.Write(tempRow[i].ToString());
}
}
Run Code Online (Sandbox Code Playgroud) 我试图将xml文件放入数据集中并使用以下代码:
DataSet ds = new DataSet("TestDataSet");
ds.ReadXml(FileName);
Run Code Online (Sandbox Code Playgroud)
和这个xml文件:
<Catalog>
<Rec>
<ITEM dt:dt="string"/>
<QTY dt:dt="string">1</QTY>
<SUB dt:dt="string">1</SUB>
<CATALOG dt:dt="string">ABC123</CATALOG>
</Rec>
<Rec>
<ITEM dt:dt="string"/>
<QTY dt:dt="string">1</QTY>
<SUB dt:dt="string">1</SUB>
<CATALOG dt:dt="string">ABC124</CATALOG>
</Rec>
<Rec>
<ITEM dt:dt="string"/>
<QTY dt:dt="string">1</QTY>
<SUB dt:dt="string">1</SUB>
<CATALOG dt:dt="string">ABC125</CATALOG>
</Rec>
</Catalog>
Run Code Online (Sandbox Code Playgroud)
麻烦的是,在ds上设置监视之后,它似乎只包含一个名为Rec的表和一个名为Rec_Id的列.如果我删除"dt:dt ="String""数据类型一切正常.
我正在使用C#.net 2008 ...
有人可以告诉您导入此数据的正确方法,而无需更改xml文件吗?
谢谢
情况:
我正在使用C#,我需要从excel文件中读取内容.excel文件中的内容与图像看起来相似.
第一列是标准,第二列是标准的数量.这些内容将有超过1000行,并将放在excel文件的最后一页.
我正在尝试使用File Helper从excel中读取内容.但是从提供的示例中,我只知道我可以读取文本文件但不能读取excel文件.
问题: