private void button2_Click(object sender, System.EventArgs e)
        {
            string sql, xq1, xq2;
            xq1 = textBox2.Text.Trim() + numericUpDown1.Value.ToString();
            xq2 = textBox3.Text.Trim() + numericUpDown2.Value.ToString();
            sql = "select ScoreId as 编号,Course as 课程,Score as 成绩,cstr(cint(Semester/10))+'-'+cstr(cint(Semester/10)+1)+'年度第'+cstr(Semester mod 10)+'学期' as 学期 from ScoreInfo where StudentNumber='" + textBox1.Text.Trim() + "' and Semester between '" + xq1 + "'and '" + xq2 + "' order by Semester desc";
            OleDbDataAdapter adp = new OleDbDataAdapter(sql, oleDbConnection1);
            DataSet ds = new DataSet();
            adp.Fill(ds, "score");
            AddExcel(ds);

        }

        protected void AddExcel(DataSet ds)
        {
            DataTable dt = ds.Tables["score"];
            string fileName = Guid.NewGuid() + ".xls";
            Excel.Application excel = new Excel.ApplicationClass();
            int rowIndex = 1;
            int colIndex = 0;
            excel.Application.Workbooks.Add(true);

            foreach (DataColumn col in dt.Columns)
            {
                colIndex++;
                excel.Cells[1, colIndex] = col.ColumnName;
            }
            foreach (DataRow row in dt.Rows)
            {
                rowIndex++;
                colIndex = 0;
                for (colIndex = 0; colIndex < dt.Columns.Count; colIndex++)
                {
                    excel.Cells[rowIndex, colIndex + 1] = row[colIndex].ToString();
                }
            }
            excel.Visible = false;
            excel.ActiveWorkbook.SaveAs(fileName, Excel.XlFileFormat.xlExcel9795, null, null, false, false, Excel.XlSaveAsAccessMode.xlNoChange, null, null, null, null, null);
            excel.Quit();
            excel = null;
            GC.Collect();
        }



本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/loveqiudexiaochouyu/archive/2010/05/30/5634667.aspx