簡體   English   中英

將數據集導出到EXCEL

[英]EXPORT Dataset 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();
        }
    }

在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

您可以根據需要進行內部或外部數據提取

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

另一個解決方案是檢索所需的任意數量的數據集,並將它們導出到同一ExcelApp中的不同工作簿中。 為此,您應該將Excel.Application xlApp取出作為全局變量。

關於保存步驟和消息框的內容,只需遵循此非常方便的指南即可將excel與c#互操作 昨天我剛剛測試了它的味道。

這應該像這樣:

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