简体   繁体   English

将数据集导出到EXCEL

[英]EXPORT Dataset to EXCEL

I am using the following code to export fields from a database table into excel. 我正在使用以下代码将字段从数据库表导出到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. 我想做的是能够编写一条SQL语句从多个表中检索字段并将其导出到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();
        }
    }

It is not safe to perform Office Automation in an ASP.NET environment. 在ASP.NET环境中执行Office Automation是不安全的。 Instead you should generate a csv, html table, or xlsx file and send it to the client. 相反,您应该生成一个csv,html表或xlsx文件,并将其发送给客户端。 For xlsx you can use the Office Open XML SDK to simplify things slightly. 对于xlsx,您可以使用Office Open XML SDK进行一些简化。

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

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. 这是在客户端系统上显示SaveAs对话框,以保存Excel工作表。

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();

Another solution is to retrieve as many datasets as you want and export them into different workbooks in the Same ExcelApp. 另一个解决方案是检索所需的任意数量的数据集,并将它们导出到同一ExcelApp中的不同工作簿中。 To do so You should take out the Excel.Application xlApp out as a global variable. 为此,您应该将Excel.Application xlApp取出作为全局变量。

Concerning the saving step and message box stuff, just follow this very convenient guide to excel interop with c# . 关于保存步骤和消息框的内容,只需遵循此非常方便的指南即可将excel与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...);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM