当前位置:文章写作网 >日记 >日记 >c#中dataGridView中的数据输出到excel源代码

c#中dataGridView中的数据输出到excel源代码

2007-09-27 14:16 作者:tshfang 阅读量:13920 推荐19次 | 我要投稿

刚接触c#,有不足之处望各位大虾排砖,小弟不胜感谢。

// 输出按钮弹出保存对话框

private void button55_Click(object sender, EventArgs e)

{

saveFileDialog1.ShowDialog();

}

private void saveFileDialog1_FileOk(object sender, CancelEventArgs e)

{

//连接数据库,设置dataGridView属性

conn = new SqlConnection(source);

sql = "Select * FROM kehujilu ";

try

{

adapter= new SqlDataAdapter(queryString, conn);

ds = new DataSet();

adapter.Fill(ds);

dataGridView1.DataSource = ds.Tables[0].DefaultView;

}

catch (SqlException ee)

{

Console.Write(ee);

throw ee;

}

saveFileDialog1.InitialDirectory = "c:\\";

lujing = saveFileDialog1.FileName;

System.Data.DataTable dtSelect = (System.Data.DataTable)(ds.Tables[0]);

int rowIndex = dtSelect.Rows.Count;

int colIndex = dtSelect.Columns.Count;

//获得excel对象

Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();

app.Visible = false;

Workbooks workbooks = app.Workbooks;

_Workbook workbook = workbooks.Add(XlWBATemplate.xlWBATWorksheet);

Sheets sheets = workbook.Worksheets;

_Worksheet worksheet = (_Worksheet)sheets.get_Item(1);

int hang = dtSelect.Rows.Count;

int lie = dtSelect.Columns.Count;

//设置excel表头

Range range1 = worksheet.get_Range("A1", "A1");

range1.Value2 = "社团名称";

Range range2 = worksheet.get_Range("b1", "b1");

range2.Value2 = "姓名";

Range range3 = worksheet.get_Range("c1", "c1");

range3.Value2 = "职务";

Range range4 = worksheet.get_Range("d1", "d1");

range4.Value2 = "电话1";

Range range5 = worksheet.get_Range("e1", "e1");

range5.Value2 = "电话2";

Range range6 = worksheet.get_Range("f1", "f1");

range6.Value2 = "电话3";

Range range7 = worksheet.get_Range("g1", "g1");

range7.Value2 = "传真1";

Range range8 = worksheet.get_Range("h1", "h1");

range8.Value2 = "传真2";

Range range9 = worksheet.get_Range("i1", "i1");

range9.Value2 = "传真3";

Range range10 = worksheet.get_Range("j1", "j1");

range10.Value2 = "手机";

Range range11 = worksheet.get_Range("k1", "k1");

range11.Value2 = "电子邮件";

Range range12 = worksheet.get_Range("l1", "l1");

range12.Value2 = "录入员";

Range range13 = worksheet.get_Range("m1", "m1");

range13.Value2 = "录入日期";

//数据输出到excel

for (int j = 0; j < hang; j++)

for (int i = 0; i < lie; i++)

{

worksheet.Cells[j + 2, i + 1] = dtSelect.Rows[j][i].ToString();

}

//保存excel,并释放内存。

workbook.SaveCopyAs(lujing);

workbook.Saved = true;

app.UserControl = false;

app.Quit();

MessageBox.Show("输出成功!");

}

这种方法不会造成在系统进程中产生excel进程。

其他人在看啥

    《c#中dataGridView中的数据输出到excel源代码》的评论 (共 0 条)

    • Guest::piaoliang
    • 叶星涵:哇,感觉很像富强哥哥
    • haoxiaozhenfang:你好 Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application(); 是不是要命名空间啊? 找不到 会出错 谢谢