public void DownloadData(object sender, EventArgs e)
{
string connectionString = "数据库信息";
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
connection.Open();
//模糊搜索
string query = "SELECT * FROM tb_cvte_mainboard_testpoints WHERE 1=1";
if (mohu_kehu.Text != "")
{
query += " AND 客户名称 LIKE '%" + mohu_kehu.Text + "%'";
}
if (mohu_type.Text != "")
{
query += " AND 器件类型 LIKE '%" + mohu_type.Text + "%'";
}
if (mohu_fenlei.Text != "")
{
query += " AND 细分类 LIKE '%" + mohu_fenlei.Text + "%'";
}
MySqlCommand command = new MySqlCommand(query, connection);
using (MySqlDataReader reader = command.ExecuteReader())
{
// 创建一个StringBuilder对象来保存CSV数据
var csvData = new System.Text.StringBuilder();
// 写入列标题
for (int i = 0; i < reader.FieldCount; i++)
{
csvData.Append(reader.GetName(i));
if (i < reader.FieldCount - 1)
{
csvData.Append(",");
}
}
csvData.AppendLine();
// 写入数据行
while (reader.Read())
{
for (int i = 0; i < reader.FieldCount; i++)
{
csvData.Append(reader.GetValue(i));
if (i < reader.FieldCount - 1)
{
csvData.Append(",");
}
}
csvData.AppendLine();
}
//csvData.AppendLine("文字");
// 设置响应头
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "text/csv";
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + "mainboard derating_" + DateTime.Now.ToString("yyyyMMdd HHmmss") + ".csv");
// 将CSV数据写入响应流
HttpContext.Current.Response.Write(csvData.ToString());
HttpContext.Current.Response.End();
}
}
}
持续更新中... ... 点个关注和收藏哦
Labview、Python、VBA、C、Excel公式、PCB Layout、PIC单片机、Visual Studio(ASP.NET)、SQL Server ,欢迎沟通讨论
部分文档为做项目过程中的源代码,可能没有注释,有疑问欢迎私信沟通#电子爱好者 #电子专业 #熟悉开关电源原理和测试 #从事硬件自动测试开发