Skip to content

Dataset to Excel for Download

Shawn O

Asked Mar 7, 2006, 4:27 AM EST1 answer
Share
LinkedInX
I have been assigned the task to create a web application and collect data from a SQL database. I put this data into a dataset and need to allow the user to 'export' this information in a CSV and a XLS. I have the CSV completed. I need to select certain data from the dataset and put it into different Excel sheets. When i go to write to a row in the excel file, I get a response from Visual Studio that I cannot write to the 'range' due to its protection level. I have pasted some code below. What am I missing?

C#
if (dt1 != null)
{
foreach (DataRow dr in dt1.Rows)
{
foreach (DataColumn dc in dr.Table.Columns)
{
    dataLine = dataLine + dr[dc] + ",";
    }
              dataLine = dataLine.Substring(0, dataLine.Length - 1);
              dataLine = dataLine + "\n";
              ws.Cells.Text = dataLine;
              //((Range)ws.Cells["1", "A"]).Value2 = dataLine; // set the cell value at a row and column
    }
}

1 Answer

Know the answer? Post it. Somebody with the same question will find it here.

  • 0
    assuming ws is a valid worksheet - try using 

        Range range = ws.get_Range("A1", Missing.Value);
        range.Value2 = "Hello";

    note calling this in a loop is slow (due to OLE overhead) - its better to use 
        Range range = ws.get_Range("A1..A"+CountOfData.ToString(), Missing.Value);
    and then loop through the range values setting them..

    good hunting
    0