开发者

Export Oracle Data with ODP.NET into an Excel File with C Sharp

I am trying to export query result sets into an excel sheet. I need to run 8 queries, each of which will be a different sheet in the excel file. I also need to add a bit of formatting around the sheet (adding a header, making the report look nice, etc).

Currently, my code is just running a single query (so only a single sheet of data). This takes a LONG time to fill out 4000 rows with 7 columns and thats a tiny sample. Is there are better way to do this? Thanks so much!

Excel.Application xlApp;
        Excel.Workbook xlWorkBook;
        Excel.Worksheet xlWorkSheet;
        object misValue = System.Reflection.Missin开发者_StackOverflow社区g.Value;
        string data = null;
        int i = 0;
        int j = 0; 

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

        string cs = "oracle connection string filtered for online posting";

        DataSet ds = new DataSet();

        OracleConnection oconn = new OracleConnection(cs);
        oconn.Open();
        Model_Netstat netstat = new Model_Netstat();
        OracleCommand oc = new OracleCommand(netstat.queryNetstatAll(session.caseName), oconn);
        oc.CommandType = CommandType.Text;

        OracleDataAdapter oda = new OracleDataAdapter(oc);
        try
        {

            oda.Fill(ds);
        } catch(Exception ex)
        {
            Console.Write(ex.Message);
        }

        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("test.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);


Check the free OpenXML SDK 2 from Microsoft out, it does what you need without automation and that's much faster and is usable in ASP.NET too (automation is not supported there)...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜