本文主要是介绍C#winform点击按钮下载数据库中表的字段到Excel上,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
C#winform点击按钮下载数据库中表的字段到Excel上
需求:C#winform点击按钮下载数据库中表的字段到Excel,并计算下载消耗的时间以及文件存放位置。
C#实现
using System;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Net;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
using OfficeOpenXml;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.Net.Http;namespace WindowsFormsApp1
{public partial class 下载表字段 : Form{/ 数据库连接字符串private string connectionString = "server=127.0.0.1;uid=sa;pwd=xyz@0123456;database=test";private async void buttonDownload_Click(object sender, EventArgs e){using (SaveFileDialog saveFileDialog = new SaveFileDialog()){saveFileDialog.Filter = "Excel files (*.xlsx)|*.xlsx";saveFileDialog.Title = "Save Excel Template";saveFileDialog.FileName = "用户模板";if (saveFileDialog.ShowDialog() == DialogResult.OK){string savePath = saveFileDialog.FileName;try{// 连接到 SQL Server 数据库using (SqlConnection sqlConnection = new SqlConnection(connectionString)){await sqlConnection.OpenAsync();// 从数据库中读取字段名using (SqlCommand command = new SqlCommand("SELECT * FROM Employee", sqlConnection))using (SqlDataReader reader = await command.ExecuteReaderAsync()){// 获取字段数量int totalColumns = reader.FieldCount;// 初始化进度条progressBar1.Maximum = totalColumns + 1;progressBar1.Value = 0;// 创建 Excel 文件using (ExcelPackage excelPackage = new ExcelPackage()){ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets.Add("Template");// 写入字段名int columnIndex = 1;for (int i = 0; i < totalColumns; i++){worksheet.Cells[1, columnIndex].Value = reader.GetName(i);columnIndex++;// 更新进度条progressBar1.Value++;await Task.Delay(10); // 延时以更新进度条显示}excelPackage.SaveAs(new FileInfo(savePath));}}// 计算所导出Excel消耗的时间//TimeSpan elapsedTime = DateTime.Now - startTime;//MessageBox.Show("导出Excel消耗时间: " + elapsedTime.ToString("g"));// 计算所导出 Excel 消耗的时间(秒)TimeSpan elapsedTime = DateTime.Now - startTime;double seconds = elapsedTime.TotalSeconds;//MessageBox.Show("导出 Excel 消耗时间: " + seconds.ToString("F2") + " 秒");MessageBox.Show("下载完成。" + "文件存放位置:" + savePath + "导出 Excel 消耗时间: " + seconds.ToString("F2") + " 秒");// 打开文件//System.Diagnostics.Process.Start(savePath);}}catch (Exception ex){MessageBox.Show("下载出错:" + ex.Message);}}}}}
}
这篇关于C#winform点击按钮下载数据库中表的字段到Excel上的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!