将数据集导出到EXCEL

时间:2011-02-12 20:32:47

标签: c# asp.net export-to-excel

我使用以下代码将数据库表中的字段导出到excel中。我想要做的是能够编写一个SQL语句来从多个表中检索字段并将它们导出到excel中。此代码仅允许我导出一个表。另外,如何显示保存提示对话框?示例代码将不胜感激 - 非常感谢!

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

3 个答案:

答案 0 :(得分:1)

在ASP.NET环境中执行Office Automation是不安全的。相反,您应该生成csv,html表或xlsx文件并将其发送到客户端。对于xlsx,您可以使用Office Open XML SDK轻微简化操作。

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

答案 1 :(得分:0)

您可以根据需要执行内部或外部来获取数据

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

否则,如果表格不相关,那么您可以通过此方式获取数据

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

这是在客户端系统上显示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();

答案 2 :(得分:0)

另一种解决方案是根据需要检索任意数量的数据集,并将它们导出到同一ExcelApp中的不同工作簿中。为此,您应该将Excel.Application xlApp取出作为全局变量。

关于保存步骤和消息框内容,请按照非常方便的guide to excel interop with c#进行操作。我昨天刚刚测试过它很甜蜜。

这应该是这样的:

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