使用 C# 读取 Excel 工作表,其中表已合并单元格

本文关键字:合并 单元格 读取 Excel 工作 使用 | 更新日期: 2023-09-27 18:37:18

我正在尝试使用 C# 读取包含一些合并单元格的 Excel 工作表。 我在另一篇文章中读到,从代码的角度来看,合并的单元格仍然存在,但它们只有空值。 所以我尝试跳过空值,但我仍然得到不稳定的结果。 这是我正在使用的代码。 它应该用电子表格中的值填充 HTML 表:

private void Output_Excel_File()
{
    string inputFileLocation = AppDomain.CurrentDomain.BaseDirectory + "/dashboard.xls";
    DataSet ds = Get_Spreadsheet_Data(inputFileLocation, "Dashboard Statistics");
    if (ds.Tables.Count > 0)
    {
        foreach (DataTable dt in ds.Tables)
        {
            int row = 0;
            foreach (DataRow dr in dt.Rows)
            {
                int col = 0;
                foreach (DataColumn dc in dt.Columns)
                {
                    string cellValue = dr[dc].ToString();
                    cellValue = Regex.Replace(cellValue, "'n", "<br /");
                    if (cellValue == "X" || cellValue == null)
                    {
                        col++;
                        continue;
                    }
                    string index = "r" + row.ToString() + "c" + col.ToString();
                    Literal cellTarget = (Literal)form1.FindControl(index);
                    cellTarget.Text = cellValue;
                    col++;
                }
                row++;
            }
        }
    }
}

特别是我的索引是关闭的,并且行:

cellTarget.Text = cellValue;

当索引与 HTML 中的索引不匹配时,总是最终会引发空引用异常。

我用谷歌搜索过,但我很困惑。 任何建议不胜感激。

使用 C# 读取 Excel 工作表,其中表已合并单元格

据我所知,合并单元格的最左上角单元格将携带数据。合并组中的所有其他单元格引用将为空。

编辑:如果你想跳过处理 r0c1(因为我假设它不存在),如果它是"X"或 Null,那么你必须做这样的事情:

foreach (DataColumn dc in dt.Columns)
{
    string cellValue = dr[dc].ToString();
    cellValue = Regex.Replace(cellValue, "'n", "<br /"); 
    if (cellValue != "X" | cellValue != null)
    {
        string index = "r" + row.ToString() + "c" + col.ToString();
        Literal cellTarget = (Literal)form1.FindControl(index);
        cellTarget.Text = cellValue; 
    }
    col++;
}

另外,我认为cellValue永远不会为空,但它可能是空的""所以我喜欢使用:

if (cellValue != "X" | cellValue.Length == 0) 

编辑2:

您可能会对收到的NullRefference异常感到有些困惑。在我看来,不是因为cellValue为空,而是来自:

(Literal)form1.FindControl(index);

试图找到我认为不存在的 r0c1 并返回一个空控件(文字)。所以当你去使用

cellTarget.Text = cellValue;

您会收到 Null引用错误,因为对象本身cellTarget为 null。