EXPORT Dataset to EXCEL

2019-07-21 10:13发布

问题:

I am using the following code to export fields from a database table into excel. What I want to do is be able to write a SQL statement to retrieve fields from multiple tables and export them into excel. This code only allows me to export one table. Also, how can I display a save prompt dialog? Sample code would be appreciated - many thanks!

protected void export_Click(object sender, EventArgs e)
{

        string sql = null;
        string data = null;
        string path = save_as.Text;

        int i = 0;
        int j = 0;

        Excel.Application xlApp;
        Excel.Workbook xlWorkBook;
        Excel.Worksheet xlWorkSheet;
        object misValue = System.Reflection.Missing.Value;

        xlApp = new Excel.ApplicationClass();
        xlWorkBook = xlApp.Workbooks.Add(misValue);
        xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

        //connectionString = "data source=servername;initial catalog=databasename;user id=username;password=password;";
        SqlConnection cnn = new SqlConnection(GetConnectionString());
        cnn.Open();
        sql = "SELECT Story, CreationDate FROM Story";
        SqlDataAdapter dscmd = new SqlDataAdapter(sql, cnn);
        DataSet ds = new DataSet();
        dscmd.Fill(ds);

        for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
        {
            for (j = 0; j <= ds.Tables[0].Columns.Count - 1; j++)
            {
                data = ds.Tables[0].Rows[i].ItemArray[j].ToString();
                xlWorkSheet.Cells[i + 1, j + 1] = data;
            }
        }

        xlWorkBook.SaveAs(path+".xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
        xlWorkBook.Close(true, misValue, misValue);
        xlApp.Quit();

        releaseObject(xlWorkSheet);
        releaseObject(xlWorkBook);
        releaseObject(xlApp);

        //MessageBox.Show("Excel file created , you can find the file c:\\csharp.net-informations.xls");
    }

    private void releaseObject(object obj)
    {
        try
        {
            System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
            obj = null;
        }
        catch (Exception ex)
        {
            obj = null;
            //MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
        }
        finally
        {
            GC.Collect();
        }
    }

回答1:

It is not safe to perform Office Automation in an ASP.NET environment. Instead you should generate a csv, html table, or xlsx file and send it to the client. For xlsx you can use the Office Open XML SDK to simplify things slightly.

http://www.microsoft.com/downloads/en/details.aspx?FamilyID=c6e744e5-36e9-45f5-8d8c-331df206e0d0&displaylang=en



回答2:

You can do inner or outter to fetch data based on your requirements

// your sql query would be look like this
sql = "SELECT Story, CreationDate, otherTableColumn_1 FROM Story inner join otherTable on Story.commonField = otherTable.commonField";

Otherwise, if the tables are not interrelated, so you can fetch data by this

// your sql query would be look like this
sql = "SELECT Story, CreationDate, otherTableColumn_1 FROM Story, otherTable";

And here is to display SaveAs dialog on client system to save the excel sheet.

Response.Clear();
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment; filename=" yourfilename.xls");
// specify excel file format, could be 2000, XP, 2003, e.t.c
workbook.SaveToStream(Response.OutputStream, FileFormat.XLS97);
Response.End();


回答3:

Another solution is to retrieve as many datasets as you want and export them into different workbooks in the Same ExcelApp. To do so You should take out the Excel.Application xlApp out as a global variable.

Concerning the saving step and message box stuff, just follow this very convenient guide to excel interop with c#. I've just tested it yesterday it's sweet.

This should go like this :

DialogResult iRet = MessageBox.Show( sMsg, "Save Data?", 
        MessageBoxButtons.YesNo );
    if (iRet == DialogResult.Yes)
           xlWorkBook.SaveAs(path+".xls", 
               Excel.XlFileFormat.xlWorkbookNormal, etc...);