码迷,mamicode.com
首页 > 数据库 > 详细

c#导出数据(数据库)到Excel

时间:2021-02-27 12:58:44      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:box   pad   dialog   prompt   source   cto   mys   index   filter   

转自:原文链接:https://blog.csdn.net/wwq0813/article/details/93294416

1. IO基础流的操作类,简单快捷:生成Excel文件,但不能在已有的Excel上插入数据

using System.IO;
using System.Threading;

 

/// <summary>
/// 导出excel方法
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void btnExport_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Excel files (*.xls)|*.xls";
saveFileDialog.FilterIndex = 0;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.CreatePrompt = true;
saveFileDialog.Title = "导出Excel文件到";

DateTime now = DateTime.Now;
saveFileDialog.FileName = now.Year.ToString().PadLeft(2)
+ now.Month.ToString().PadLeft(2, ‘0‘)
+ now.Day.ToString().PadLeft(2, ‘0‘) + "-"
+ now.Hour.ToString().PadLeft(2, ‘0‘)
+ now.Minute.ToString().PadLeft(2, ‘0‘)
+ now.Second.ToString().PadLeft(2, ‘0‘);
saveFileDialog.ShowDialog();

Stream myStream = saveFileDialog.OpenFile();
StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding("gb2312"));
string str = "";

//写标题
for (int i = 0; i < ((DataTable)dataGridView1.DataSource).Columns.Count; i++)
{
if (i > 0)
{
str += "\t";
}
str += ((DataTable)dataGridView1.DataSource).Columns[i];
}
sw.WriteLine(str);
//写内容
for (int j = 0; j < ((DataTable)dataGridView1.DataSource).Rows.Count; j++)
{
string tempStr = "";
for (int k = 0; k < ((DataTable)dataGridView1.DataSource).Columns.Count; k++)
{
if (k > 0)
{
tempStr += "\t";
}
tempStr += ((DataTable)dataGridView1.DataSource).Rows[j][k].ToString();
}
sw.WriteLine(tempStr);

}
sw.Close();

myStream.Close();

MessageBox.Show("导出成功");
}

c#导出数据(数据库)到Excel

标签:box   pad   dialog   prompt   source   cto   mys   index   filter   

原文地址:https://www.cnblogs.com/-GoFurther/p/14451680.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!