0

C#を使用していくつかのセルが結合されたExcelシートを読み込もうとしています。別の投稿で、マージされたセルはコードの観点からはまだ存在していましたが、null値しかなかったと読みました。そのため、null値をスキップしようとしましたが、それでも不安定な結果が得られます。これが私が使用しているコードです。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のインデックスと一致しなくなると、常にnull参照例外がスローされます。

私はグーグルとグーグルをしましたが、私は困惑しています。アドバイスをいただければ幸いです。

4

1 に答える 1

0

From what I remember, The upper left most cell of merged cells will carry the data. Every other cell reference in the merged group will be empty.

EDIT: If you want to skip processing r0c1 (Because I assume it doesnt exist) if it is "X" or Null, then you would have to do something like this:

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++;
}

Also I think cellValue will not ever be null, but it may be empty "" so I like to use:

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

EDIT2:

You may be a bit confused with the NullRefference exception that you are recieving. From what I see it not because the cellValue is null, it's from:

(Literal)form1.FindControl(index);

trying to find r0c1 which I assume doesn't exist and returns a null control(Literal). So when you go to use

cellTarget.Text = cellValue;

you get a NullReference error because the object itself cellTarget is null.

于 2012-06-14T17:16:08.143 に答える