excel导入sql数据库:c# 从sql 数据库生成 excel来源: 发布时间:星期一, 2008年12月1日 浏览:129次 评论:0
首先要在工程中添加com引用,选择Microsoft Excel 11.0 Object Liberty。
源代码如下(本例是在下生成公司的考勤表 测试代码): using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Data.SqlClient; using Microsoft.Office.Interop.Excel; using System.IO; //using Microsoft.Office.Interop.Excel; namespace AttToExcel { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application(); int rowIndex = 1; int colIndex = 0; excel.Application.Workbooks.Add(true); System.Data.DataTable table = GetData(); // dealTable(table); //将所得到的表的列名,赋值给单元格 foreach (DataColumn col in table.Columns) { colIndex++; excel.Cells[1, colIndex] = col.ColumnName; } //同样方法处理数据 foreach (DataRow row in table.Rows) { rowIndex++; colIndex = 0; foreach (DataColumn col in table.Columns) { colIndex++; excel.Cells[rowIndex, colIndex] = row[col.ColumnName].ToString(); } } Worksheet ws = (Worksheet)excel.ActiveSheet; AutoFitColumn(ws, 5); //true则直接用excel打开得到的数据 excel.Visible = true ; } //进行加班处理 private void dealTable(System.Data.DataTable table) { } //让excel列宽自适应宽度 public static void AutoFitColumn(Worksheet ws, int col) { ((Range)ws.Cells[1, col]).EntireColumn.AutoFit(); } //获取数据库打卡记录数据 private System.Data.DataTable GetData() { SqlConnection conn= new SqlConnection(@"Server=127.0.0.1;Initial Catalog=attendance;Uid=sa;Pwd=123456;"); String sqlText = "select "+ "EmplId as '员工ID',"+ "(select EmplName from HrEmployee where HrEmployee.EmplID=AtdProcRec.EmplID) as '姓名',"+ "case "+ "when min(RecTime)<'07:00' then max(RecTime) "+ " else min(RecTime) "+ " end as '上班时间', "+ "case when min(RecTIme)<'07:00' then min(RecTime) "+ " else max(RecTime) "+ " end as '下班时间', "+ "ResultDate as '结果日期'"+ " from dbo.AtdProcRec"+ " where EmplID=34 "+ "group by ResultDate,EmplId";//+ //"having min(RecTime)>'09:00' or max(Rectime)<'17:30'"; SqlDataAdapter adapter = new SqlDataAdapter(sqlText, conn); DataSet ds= new DataSet(); try { adapter.Fill(ds,"Customer"); } catch(Exception ex) { MessageBox.Show(ex.ToString()); } return ds.Tables[0]; }//end GetData() }//end public partial class }//end namespace 0
相关文章
读者评论
发表评论 |