- private DataSet bangding()
- {
- using (SqlConnection conn = new SqlConnection("server=.;uid=sa;pwd=;database=pubs"))
- {
- conn.Open();
- string sql = "select job_id as 编号,job_desc as 排序,min_lvl as 最小, max_lvl as 最大 from jobs";
- SqlDataAdapter dar = new SqlDataAdapter(sql, conn);
- DataSet ds = new DataSet();
- dar.Fill(ds);
- this.GridView1.DataSource = ds;
- this.GridView1.DataBind();
- return ds;
- }
- }
- private int num()
- {
- int num=0;
- for (int i = 0; i < bangding().Tables[0].Rows.Count;i++ )
- {
- num += Convert.ToInt32(bangding().Tables[0].Rows[i][3].ToString());
- }
- return num;
- }
- protected void Button1_Click(object sender, EventArgs e)
- {
- CreateExcel(bangding(), "D:/aa.xls", "标题", "合计:" + num());
- }
- public void CreateExcel(DataSet dv, string path, string title1, string heji)
- {
- try
- {
- FileInfo fi = new FileInfo(path);
- fi.Delete();
- }
- catch
- {
- }
- Microsoft.Office.Interop.Excel.Application excel = new Application();
- object oMissing = System.Reflection.Missing.Value;
- Microsoft.Office.Interop.Excel.Workbook book = excel.Workbooks.Add(oMissing);
- int rowIndex = 3;
- int colIndex = 0;
- excel.Cells[1, 1] = title1;
- foreach (DataColumn dc in dv.Tables[0].Columns)
- {
- colIndex++;
- excel.Cells[rowIndex, colIndex] = dc.ColumnName;
- ((Microsoft.Office.Interop.Excel.Range)excel.Cells[rowIndex, colIndex]).ColumnWidth = 18.8;
- }
- foreach (DataRow row in dv.Tables[0].Rows)
- {
- rowIndex++;
- colIndex = 0;
- foreach (DataColumn dc in dv.Tables[0].Columns)
- {
- colIndex++;
- excel.Cells[rowIndex, colIndex] = row[dc.ColumnName].ToString();
- ((Microsoft.Office.Interop.Excel.Range)excel.Cells[rowIndex, colIndex]).ColumnWidth = 18.8;
- }
- }
- excel.Cells[rowIndex + 1, colIndex] = heji;
- Microsoft.Office.Interop.Excel.Sheets sheets = book.Worksheets;
- Microsoft.Office.Interop.Excel._Worksheet worksheet = (Microsoft.Office.Interop.Excel._Worksheet)sheets.get_Item(1);
- Microsoft.Office.Interop.Excel.Range range;
- range = worksheet.get_Range(worksheet.Cells[1, 1], worksheet.Cells[1, colIndex]);
- range.MergeCells = true;//合并
- range.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;//居中
- range.Font.Bold = true;
- range.Font.Size = 14;
- book.Saved = true;
- excel.UserControl = false;
- worksheet.SaveAs(path, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);
- excel.Quit();
- oMissing = null;
- sheets = null;
- worksheet = null;
- book = null;
- excel = null;
- GC.Collect();
- }
asp.net 到出Excel 示例
最新推荐文章于 2024-09-20 15:13:09 发布