【问题标题】:Can you read an Excel xlsx row like a database row using OpenXML?您可以使用 OpenXML 像读取数据库行一样读取 Excel xlsx 行吗?
【发布时间】:2022-12-07 22:11:28
【问题描述】:

昨天我差点失去理智,因为这应该是多么容易和现实之间脱节了。工作簿正在使用共享字符串;我确实找到了一种获取单元格值的方法,但如果我可以只获取单元格中显示的内容而不是跳来跳去,那就更好了。更重要的是,我需要获取每一行的 A、B 和 C 列的值,但如果值为空,它会将其视为该单元格不存在!你能在 foreach Row 语句中填写伪代码吗?如果有一种方法可以直接获取值,那就更好了,但是你可以假设我有一个方法可以完成所有的字符串表查找。

try
{
    using (SpreadsheetDocument doc = SpreadsheetDocument.Open("C:\\temp\\sitemap.xlsx", false))
    {
        WorkbookPart workbookPart = doc.WorkbookPart;
        Sheets thesheetcollection = workbookPart.Workbook.GetFirstChild<Sheets>();
        StringBuilder excelResult = new StringBuilder();

        foreach (Sheet thesheet in thesheetcollection)
        {
            excelResult.AppendLine("Excel Sheet Name : " + thesheet.Name);
            excelResult.AppendLine("----------------------------------------------- ");

            Worksheet theWorksheet = ((WorksheetPart)workbookPart.GetPartById(thesheet.Id)).Worksheet;
            SheetData thesheetdata = (SheetData)theWorksheet.GetFirstChild<SheetData>();

            foreach (Row thecurrentrow in thesheetdata)
            {
                // Help needed here
                var val1 = thecurrentrow[0].InnerText; // Col A
                var val2 = thecurrentrow[1].InnerText; // Col B
                var val3 = thecurrentrow[2].InnerText; // Col C
            }
            excelResult.Append("");
            Console.WriteLine(excelResult.ToString());
            Console.ReadLine();
        }
    }
}
catch (Exception)
{

}

【问题讨论】:

  • 如果“它把它当作细胞不存在!”意思是“它的值为空”,赋值前检查值:var val1 = thecurrentrow[0] == null ? string.Empty : thecurrentrow[0].InnerText;
  • 除非你有充分的理由不这样做,否则你应该使用 ClosedXML 等。OpenXML 使用起来非常困难和烦人。

标签: c# openxml


【解决方案1】:

您将需要构建所有单元格地址,然后检查是否存在具有该地址的单元格。像这样:

    private void ReadExcel()
    {
        for (int rowIdx = 1; rowIdx < 100; rowIdx++)
        {
            for (int colIdx = 1; colIdx < 30; colIdx++)
            {
                string cellAdress = $"{GetExcelColumnName(colIdx)}{rowIdx}";

                DocumentFormat.OpenXml.Spreadsheet.Cell cell = theWorksheet.Descendants<DocumentFormat.OpenXml.Spreadsheet.Cell>().FirstOrDefault(c => c.CellReference == cellAdress);
                // if cell == null the cell has no value

            }
        }
    }

    private static string GetExcelColumnName(int columnNumber)
    {
        int dividend = columnNumber;
        string columnName = string.Empty;
        int modulo;

        while (dividend > 0)
        {
            modulo = (dividend - 1) % 26;
            columnName = Convert.ToChar(65 + modulo).ToString() + columnName;
            dividend = (dividend - modulo) / 26;
        }

        return columnName;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-19
    • 1970-01-01
    相关资源
    最近更新 更多