各位大侠,帮忙看看我的代码有什么问题,怎么解决?万分感谢!!!
 
protected void btnocexport_Click(object sender, EventArgs e)
    {
        StringBuilder sqlsb = new StringBuilder("SELECT ID,Date,Batch_Job,OC_Rsync,SU_Rsync FROM IT_BatchJob WHERE 1=1");        if (this.txtdate.Text.ToString() != "" && this.txtenddate.Text.ToString() == "")
            sqlsb.Append(" AND Date = '" + this.txtdate.Text.ToString().Trim().Replace("'", "''") + "'");
        if (this.txtdate.Text.ToString() != "" && this.txtenddate.Text.ToString() != "")
            sqlsb.Append(" AND Date >= '" + this.txtdate.Text.ToString().Trim().Replace("'", "''") + "' AND Date <= '" + this.txtenddate.Text.ToString().Trim().Replace("'", "''") + "'");        ViewState["_VsSql"] = sqlsb.ToString();
        //输出SQL语句
        //Response.Write(ViewState["_VsSql"]);
        using (DBSql db = new DBSql())
        {
            DataTable dt = db.QueryDt(ViewState["_VsSql"].ToString());
            string saveFileName = "";
            bool fileSaved = false;
            System.Windows.Forms.SaveFileDialog saveDialog = new System.Windows.Forms.SaveFileDialog();
            saveDialog.DefaultExt = "xls";
            saveDialog.Filter = "Excel文件|*.xls";
            saveDialog.FileName = "Sheet1";
            saveDialog.ShowDialog();//执行到这里出错:错误提示:在可以调用 OLE 之前,必须将当前线程设置为单线程单元(STA)模式。请确保您的 Main 函数带有 STAThreadAttribute 标记。 只有将调试器附加到该进程才会引发此异常。             saveFileName = saveDialog.FileName;
            if (saveFileName.IndexOf(":") < 0) return; //被点了取消             Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();            if (xlApp == null)
            {
                System.Windows.Forms.MessageBox.Show("无法创建Excel对象,可能您的机子未安装Excel");
                return;
            }            Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;
            Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
            Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];//取得Sheet1
            int rows = dt.Rows.Count; //行数
            int columns = dt.Columns.Count;//列数            Workbook book = new Workbook();
            Worksheet sheet = new Worksheet("sheet1");
            //Excel列名
            sheet.Cells[0, 0] = new Cell("ID");
            sheet.Cells[0, 1] = new Cell("Date");
            sheet.Cells[0, 2] = new Cell("Batch Job");
            sheet.Cells[0, 3] = new Cell("OC Rsync");
            sheet.Cells[0, 4] = new Cell("SU Rsync");
            string value = "";            for (int r = 0; r < rows; r++)
            {
                for (int c = 0; c < columns; c++)
                {
                    if (dt.Rows[r][c].ToString() != "&nbsp;")
                    {
                        //value = dt.Rows[r].Cells[c].Text;
                        value = dt.Rows[r][c].ToString();
                        if (value == "True")
                        {
                            sheet.Cells[r + 1, c] = new Cell(1);
                        }
                        else if (value == "False")
                        {
                            sheet.Cells[r + 1, c] = new Cell(0);
                        }
                        else
                        {
                            sheet.Cells[r + 1, c] = new Cell(value);
                        }
                    }
                }
            }            //book.Worksheets.Add(sheet);
            //book.Save(@"D:\导出.xls");
            worksheet.Columns.EntireColumn.AutoFit();//列宽自适应。
            //if (cmbxType.Text != "Notification")
            //{
            //    Excel.Range rg = worksheet.get_Range(worksheet.Cells[2, 2], worksheet.Cells[ds.Tables[0].Rows.Count + 1, 2]);
            //    rg.NumberFormat = "00000000";
            //}
            if (saveFileName != "")
            {
                try
                {
                    workbook.Saved = true;
                    workbook.SaveCopyAs(saveFileName);
                    fileSaved = true;
                }
                catch (Exception ex)
                {
                    fileSaved = false;
                    System.Windows.Forms.MessageBox.Show("导出文件时出错,文件可能正被打开!\n" + ex.Message);
                }
            }
            else
            {
                fileSaved = false;
            }
            xlApp.Quit();
            GC.Collect();//强行销毁 
            if (fileSaved && System.IO.File.Exists(saveFileName)) System.Diagnostics.Process.Start(saveFileName); //打开EXCEL        }
    }

解决方案 »

  1.   

    你的程序是03做的吧!在后台的Main函数上面要加上[STAThreadAttribute]再试试
      

  2.   


    不是的,VS2005做的,没有Main函数
      

  3.   

    给你个例子,这是个不用模板的例子,SetReportData里是填数据和样式的东西就不给你了
    /// <summary>
            /// 导出报表
            /// </summary>
            /// <param name="type">显示类型</param>
            /// <returns></returns>
            public int Report(int type)
            {
                int iRtn = -1;
                string sFileName = "";
                int iModelID = 0;
                SaveFileDialog sfd = new SaveFileDialog();
                //sfd.Filter = "*.xls|*.xls|*.xlsx|*.xlsx";
                sfd.Filter = "*.xlsx|*.xlsx";
                sfd.RestoreDirectory = true;
                switch (type)
                {
                    case (int)MonitorType.Station_Passenger_Saturation:                    if (sfd.ShowDialog() == DialogResult.OK)
                        {
                            iRtn = 0;
                            sFileName = sfd.FileName;
                            iModelID = 100000001;
                            if (!ExportWord(iModelID, sFileName))
                                iRtn = 1;
                        }                    break;
                    case (int)MonitorType.Station_Vehicles_Saturation:                    if (sfd.ShowDialog() == DialogResult.OK)
                        {
                            iRtn = 0;
                            sFileName = sfd.FileName;
                            iModelID = 100000002;
                            if (!ExportReport(iModelID, sFileName))
                                iRtn = 1;
                        }                    break;
                }            return iRtn;
            }
            /// <summary>
            /// 导出BRT站台车辆饱和度报表
            /// </summary>
            /// <param name="iModelID"></param>
            /// <param name="sFileName"></param>
            /// <returns></returns>
            private bool ExportReport(int iModelID, string sFileName)
            {
                bool bRtn = false;            #region 导出Excel
                // 准备打开Excel文件时的缺省参数对象
                object oMissing = System.Reflection.Missing.Value;            // 创建Excel对象示例
                Excel.ApplicationClass oExcel = new Excel.ApplicationClass();            // 使创建的对象不可见
                oExcel.Visible = false;            Excel.Workbooks oBooks = oExcel.Workbooks;            // 创建Workbook对象 
                Excel._Workbook oBook = oBooks.Add(true);            // 创建Workbook对象
                Excel.Worksheet sheet1 = (Excel.Worksheet)oBook.Worksheets[1];
                sheet1.Name = "BRT站台车流饱和度报表";            try
                {
                    //填充数据
                    if (!SetReportData(sheet1, iModelID))
                    {
                        //throw new Exception();
                    }                ////显示
                    //oExcel.Visible = true;                //保存                
                    oBook.SaveCopyAs(@sFileName);
                    bRtn = true;
                }
                catch
                {
                    bRtn = false;
                }
                finally
                {
                    #region 释放对象
                    //释放sheet                 
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(sheet1);
                    sheet1 = null;
                    oBook.Close(false, oMissing, oMissing);
                    // 释放Workbook对象
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(oBook);
                    oBook = null;
                    oBooks.Close();
                    // 释放Workbooks对象
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(oBooks);
                    oBooks = null;                // 关闭Excel
                    oExcel.Quit();                // 释放Excel对象
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(oExcel);
                    oExcel = null;                // 调用垃圾回收
                    GC.Collect();                #endregion
                }
                #endregion            return bRtn;
            }
      

  4.   

    请问3楼的:
    MonitorType是在哪里定义的,提示当前上下文中不存在MonitorType
      

  5.   

    MonitorType是一个枚举,为的就是判断传进来的状态,其实就是个ID不一样,之后SetReportData填充数据的样式和数据不一样而已,你不用考虑这个,用一个就行了。
      

  6.   

    问题还是没有解决,每个方法用的时候都会在ShowDialog()这里报错,请各位高手帮帮忙!
      

  7.   

    ShowDialog()是前台的你用的是win32还是web注意下,看看报什么错误,给贴出来
      

  8.   

    错误提示:在可以调用 OLE 之前,必须将当前线程设置为单线程单元(STA)模式。请确保您的 Main 函数带有 STAThreadAttribute 标记。 只有将调试器附加到该进程才会引发此异常。