我想利用sql语句直接将数据库中的数据导出到excel模版中去,大家帮我看看这样写对不对?应该怎么写呢?我运行的时候总是没有结果,也没有错误,就是页面一直在运行,就是不结束,但如果我逐步调试的话,又是可以运行的,我觉得很奇怪。主要是用了QueryTable.Add的方法.还有,设置那些QueryTable的属性是用来干什么的?谁能帮我解释一下? 谢谢大家了。 public void ExportToExcel(string pstrSql)
{
Excel.ApplicationClass pApplication = new Excel.ApplicationClass();;
Excel._Workbook xBk = null;
Excel.Workbooks xBks = null;
Excel._Worksheet xSt = null;
Excel._QueryTable xQt = null;
Excel.QueryTables xQts = null; string ExcelConn = "Provider=Microsoft.Jet.OleDb.4.0;Data Source=" + HttpContext.Current.Server.MapPath("test.mdb"); object Nothing=System.Reflection.Missing.Value;
string FileName = HttpContext.Current.Server.MapPath("./")+"/4.xls";
xBks = pApplication.Application.Workbooks;
xBk = xBks.Open(FileName,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing,Nothing);
xSt = (Excel._Worksheet)xBk.ActiveSheet;
xSt.Rows.ClearContents(); xSt.get_Range(pApplication.Cells[2,2],pApplication.Cells[2,2]).Font.Bold = true;
xSt.get_Range(pApplication.Cells[2,2],pApplication.Cells[2,2]).Font.Name = "黑体";
xSt.get_Range(pApplication.Cells[2,2],pApplication.Cells[2,2]).Font.Size = 22; xQts = xSt.QueryTables; xQt = xQts.Add("OLEDB;Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+ HttpContext.Current.Server.MapPath("test.mdb"), xSt.get_Range(pApplication.Cells[1,1],pApplication.Cells[1,1]), pstrSql) ;
xQt.Name = "导出EXCEL";
xQt.FieldNames = true;
xQt.RowNumbers = false;
xQt.FillAdjacentFormulas = false;
xQt.PreserveFormatting = false;
xQt.BackgroundQuery = true;
xQt.RefreshStyle = Excel.XlCellInsertionMode.xlInsertDeleteCells;
xQt.AdjustColumnWidth = true;
xQt.RefreshPeriod = 0;
xQt.PreserveColumnInfo = true;
xQt.Refresh(xQt.BackgroundQuery); xBk.Save();
                           xBk.Close(true, FileName, false); pApplication.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(xSt);
System.Runtime.InteropServices.Marshal.ReleaseComObject(xQts);
System.Runtime.InteropServices.Marshal.ReleaseComObject(xBk);
System.Runtime.InteropServices.Marshal.ReleaseComObject(xBks);
System.Runtime.InteropServices.Marshal.ReleaseComObject(xQt);
System.Runtime.InteropServices.Marshal.ReleaseComObject(pApplication);

xSt=null;
xQts=null;
xBk=null;
xBks=null;
xQt=null;
xQts=null;
pApplication=null;
             }