博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
winform简单代码导出Execl
阅读量:6511 次
发布时间:2019-06-24

本文共 1953 字,大约阅读时间需要 6 分钟。

private void DataToExecl()         {
if (this.dgTemp.Rows.Count > 0)//dgTemp为DataGridView控件 {
SaveFileDialog sfd = new SaveFileDialog(); sfd.Title = "导出到Execl"; sfd.DefaultExt = "xls"; sfd.Filter = "Execl文件(*.xls)|.xls"; sfd.FilterIndex = 0; sfd.RestoreDirectory = true; sfd.CreatePrompt = true; sfd.FileName = "XXXX.xls";//导出xls的文件名 sfd.ShowDialog(); if (sfd.FileName == "") {
return; } Stream stream = sfd.OpenFile(); StreamWriter sw = new StreamWriter(stream, System.Text.Encoding.GetEncoding(-0)); try {
string str1 = ""; for (int i = 0; i < this.dgTemp.ColumnCount; i++) {
if (str1 != "") {
str1 += "\t"; } str1 += dgTemp.Columns[i].HeaderText; } sw.WriteLine(str1); for (int j = 0; j < dgTemp.Rows.Count; j++) {
string str2 = ""; for (int k = 0; k < dgTemp.Columns.Count; k++) {
if (str2 != "") {
str2 += "\t"; } str2 += dgTemp.Rows[j].Cells[k].Value.ToString(); } sw.WriteLine(str2); } sw.Close(); stream.Close(); } catch (Exception ex) {
MessageBox.Show(ex.ToString()); } finally {
sw.Close(); stream.Close(); } } }

 

转载于:https://www.cnblogs.com/IT-SmallBird/archive/2011/11/29/2268048.html

你可能感兴趣的文章