【问题标题】:Reading Excel Sheet Using C# Where the Table has Merged Cells使用 C# 读取 Excel 工作表,其中表格已合并单元格
【发布时间】:2012-06-14 17:12:00
【问题描述】:

我正在尝试使用 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 中的索引不匹配时,总是会抛出空引用异常。

我已经用谷歌搜索了又谷歌,但我很困惑。任何建议表示赞赏。

【问题讨论】:

  • Get_Spreadsheet_Data 是做什么的?这是图书馆吗?哪一个?
  • 这段代码是由有经验的人提供给我的。我只是假设它有效。当我调试时,我确实在变量中看到了电子表格中的值,但索引已关闭,我不知道为什么。

标签: c# asp.net html-table import-from-excel


【解决方案1】:

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

编辑: 如果你想跳过处理 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) 

EDIT2:

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

(Literal)form1.FindControl(index);

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

cellTarget.Text = cellValue;

您收到 NullReference 错误,因为对象本身 cellTarget 为空。

【讨论】:

  • 这就是我跳过返回空值的单元格的原因。但我的索引仍然关闭。
  • 看起来你的index第一次在循环中位于int col = 0;int row = 0;的R0C0string index = "r" + row.ToString() + "c" + col.ToString();
  • 我在 HTML 表中替换的文字控件具有 id="r0c0"。出于某种原因,即使表格的第一行中只有一个值,我的索引也会前进到 r0c1 —— 所有单元格都被合并了。
  • 嗯。我的表是 5x5,第一行是 5 个合并列,只包含一个标题。我的理解是,要遍历这一行,我仍然必须遍历合并的单元格,但它们将具有空值。因此跳过空值应该有效,不是吗?
  • 是的,但是您每次都在打线Literal cellTarget = (Literal)form1.FindControl(index);。我编辑了我的答案以寻求帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-05-11
  • 1970-01-01
  • 2017-04-19
  • 2014-05-21
  • 1970-01-01
  • 2015-07-26
  • 2017-01-27
相关资源
最近更新 更多