views:

168

answers:

1

Hi everyone, I have a spreadsheet with multiple pages in it.When I click on a button I need to open this spreadsheet and write all the data(dataset/datatable) returned from the database into one of the pages in the spreadsheet.I saw so many articles for exporting dataset to a new excel sheet.how do i open an existing spreadsheet and write a dataset into it using asp.net/C#?

Please help..

Thanks.

UPDATE:

Basically I have the following code to export a dataset to a new excel sheet.

private void createDataInExcel(DataSet ds)
{

    Application oXL;

    _Workbook oWB;

    _Worksheet oSheet;

    Range oRng;

    string strCurrentDir = Server.MapPath(".") + "\\excelreports\\";

    try
    {

        oXL = new Application();

        oXL.Visible = false;

        //Get a new workbook.

        oWB = (_Workbook)(oXL.Workbooks.Add(Missing.Value));

        oSheet = (_Worksheet)oWB.ActiveSheet;

        //System.Data.DataTable dtGridData=ds.Tables[0];

        int iRow = 2;

        if (ds.Tables[0].Rows.Count > 0)
        {


            for (int j = 0; j < ds.Tables[0].Columns.Count; j++)
            {

                oSheet.Cells[1, j + 1] = ds.Tables[0].Columns[j].ColumnName;

            }

            // For each row, print the values of each column.

            for (int rowNo = 0; rowNo < ds.Tables[0].Rows.Count; rowNo++)
            {

                for (int colNo = 0; colNo < ds.Tables[0].Columns.Count; colNo++)
                {

                    oSheet.Cells[iRow, colNo + 1] = ds.Tables[0].Rows[rowNo][colNo].ToString();

                }
                iRow++;

            }              

        }

        oRng = oSheet.get_Range("A1", "IV1");

        oRng.EntireColumn.AutoFit();

        oXL.Visible = false;

        oXL.UserControl = false;

        string strFile = "excelreport" + DateTime.Now.Ticks.ToString() + ".xls";//+

        oWB.SaveAs(strCurrentDir +strFile, XlFileFormat.xlWorkbookNormal, null, null, false, false, XlSaveAsAccessMode.xlShared, false, false, null,null, null);

        // Need all following code to clean up and remove all references!!!

        oWB.Close(null, null, null);

        oXL.Workbooks.Close();

        oXL.Quit();

        Marshal.ReleaseComObject(oRng);

        Marshal.ReleaseComObject(oXL);

        Marshal.ReleaseComObject(oSheet);

        Marshal.ReleaseComObject(oWB);


    }

    catch (Exception theException)
    {

        Response.Write(theException.Message);

    }
    Response.Write("data exported");

}

Is it possible to improve the above code to write the dataset to an existing sheet?Also with the above code its taking about a minute to write the data into excel sheet..I do not understand why is it taking that long.

A: 

not 100% sure where you are with your code, however using the excel com object referenced in your project you can open a workbook using the Workbooks._Open method, then you can get the sheet by name using the sheets collection of the workbook and the get_Item.

if you need to add a sheet to the workbook you can use the add on the sheets collect.

Maybe if you post the code you have we can suggest where to improve it.

this line

oWB = (_Workbook)(oXL.Workbooks.Add(Missing.Value));

is creating a new workbook. use

string workbookPath = "c:/SomeWorkBook.xls";

oWB = Workbooks.Open(workbookPath,
        0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "",
        true, false, 0, true, false, false);

now it depends on what you want to do add a new sheet, use an existing sheet etc.

this is a codeproject link that shows more in depth here

Pharabus
Thanks Pharabus.Iam able to open my .xls file and write into it now.after writing into it I want to raise a file download for the excel sheet and allow the user to either open/save the file.I am writing the following lines of code after the code to write the data into excel sheet. HttpResponse response = HttpContext.Current.Response; response.AddHeader("Content-Disposition", "attachment;filename=\"Mss.xls\""); where Mss.xls is the name of my excel sheet.when I try to save this file from the download and open i see that the aspx page is copied and not the spreadsheet.please help?
kranthi
are you actually writing the file to the response stream? Response.WriteFile(FilePath); Response.End();
Pharabus
you are right Pharabus.I was not calling WriteFile().by adding the the lines given by you it works fine.The only problem I am left with is, its taking around 5o secs for my code to open the existing excel file and write the whole data.I am writing around 500 records into the excel sheet.Could this be the reason for taking such a long time?Is there a way to improve the speed?Could you please check the code in my original question, to see if there is anything wrong?
kranthi
there is nothing obviously wrong, It has to loop once for each row (so 500 times for your 500 records) but it also has to loop once per column within each row loop so, depending on how many columns a row has, that could take a while. 500 rows * 10 columns is 5000 loops
Pharabus
I have around 50 columns and 500 records in my database table which I am writing into the excel sheet.So there is no scope for improving the speed with above code.is that correct?
kranthi
unfortunately none that i can see
Pharabus