C# 导出数据到excel中
在C#做上位机开发中,经常需要将数据导出保存,常用的有两种,一个是txt,一个是excel,我在开发过程中会新建两个类,分别为txt以及txcel,当需要保存为txt时,将调用txt类里面的函数,需要保存excel内容时,将调用excel里面的函数,接口封装简单,下面对口进行一个简单的说明:
(1)excel数据导出函数:public static byte ExportDataToExcel(DataGridView dgv)
接口为DataGridView类型的表格,数据传送时,定义一个变量,如:DataGridView excel_dataGridView = new DataGridView();,然后将文件格式写入即可,代码举例说明:
//写入两列数据 第一列为序号 第二列为数据
excel_dataGridView.Columns.Add("", “序号”);
excel_dataGridView.Columns.Add("", “数据”);
//列表的一些格式配置,也可直接取消
DataGridViewCellStyle headerStyle = new DataGridViewCellStyle();
headerStyle.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter;
excel_dataGridView.ColumnHeadersDefaultCellStyle = headerStyle;
excel_dataGridView.EnableHeadersVisualStyles = false;
excel_dataGridView.ColumnHeadersDefaultCellStyle.Font = new Font(“微软雅黑”, 17, FontStyle.Bold);
excel_dataGridView.RowsDefaultCellStyle.Font = new Font(“微软雅黑”, 17);
excel_dataGridView.DefaultCellStyle.Font = new Font(“微软雅黑”, 17);
//将每一行的数据写入
for (int i = 0; i < zjm.in_out_info.sncx_list_data.Count; i++)
{
excel_dataGridView.Rows.Add();//增加一行数据
excel_dataGridView.Rows[i].Cells[0].Value = i + 1; //序号
excel_dataGridView.Rows[i].Cells[1].Value = data[i]; //数据
}
//调用函数写入数据并返回写入结果
byte temp_resu = excel.ExportDataToExcel(excel_dataGridView);
if (temp_resu == 1)
{
warning_display(“数据导出完成”);
}
else if (temp_resu == 2)
{
warning_display(“数据导出失败”);
}
else if (temp_resu == 3)
{
warning_display(“请先关闭文件再保存”);
}
else if (temp_resu == 0)
{
warning_display(“数据导出已取消”);
}
注意,引用前需要安装程序包:Microsoft.Office.Interop.Excel.
对应的excel完整的代码块如下:
using System;
using System.Collections;
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;
namespace In_Out_manage_system
{
class excel
{
//TEL:15960252022 Mr.xie
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int ID);
public static byte ExportDataToExcel(DataGridView dgv)
{
try
{
string path = "";
SaveFileDialog saveDialog = new SaveFileDialog();
saveDialog.Title = "请选择要导出的位置";
saveDialog.Filter = "Excel文件| *.xlsx;*.xls";
saveDialog.ShowDialog();
path = saveDialog.FileName;
if (path.IndexOf(":") < 0) return 0;
string FileName = saveDialog.FileName;
if (File.Exists(FileName))
File.Delete(FileName);
Microsoft.Office.Interop.Excel.Application excel