WinForm导入导出

Posted ryzryz

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了WinForm导入导出相关的知识,希望对你有一定的参考价值。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Dapper;
using System.Data.SqlClient;
using PublicToolsLib.HelpExcel;
using System.IO;
using System.Data;
namespace WindowsFormsApp2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
using (IDbConnection conn = new SqlConnection("Data Source=.;Initial Catalog=IOT1706B;Integrated Security=True"))
{
List<Student> list = conn.Query<Student>("select * from Student").ToList();
dataGridView1.DataSource = list;

}
}
private void button1_Click(object sender, EventArgs e)
{
using (IDbConnection conn = new SqlConnection("Data Source=.;Initial Catalog=IOT1706B;Integrated Security=True"))
{
List<Student> list = conn.Query<Student>("select * from Student").ToList();

DataTable dt = new DataTable("Show");
//表头
dt.Columns.Add("Id", typeof(int));
dt.Columns.Add("StuName", typeof(string));
dt.Columns.Add("StuSex", typeof(string));
dt.Columns.Add("StuHobby", typeof(string));
//行
foreach (Student item in list)
{
DataRow dr = dt.NewRow();
dr["Id"] = item.Id;
dr["StuName"] = item.StuName;
dr["StuSex"] = item.StuSex ? "男" : "女";
dr["StuHobby"] = item.StuHobby;
dt.Rows.Add(dr);
}
Dictionary<string, string> keyValuePairs = new Dictionary<string, string>()
{
{"编号","Id" },
{"姓名","StuName" },
{"性别","StuSex" },
{"爱好","StuHobby" },
};
MemoryStream memoryStream = NpoiExcelHelper.ExportExcel(dt, keyValuePairs);
//保存窗口
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Excel|*.xlsx";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
File.WriteAllBytes(saveFileDialog.FileName, memoryStream.ToArray());
MessageBox.Show("导出成功!");
}


}
}

private void button2_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "Excel|*.xlsx";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
DataTable dt = NpoiExcelHelper.ImportExcel(openFileDialog.FileName);

int n = 0;
using (IDbConnection conn = new SqlConnection("Data Source=.;Initial Catalog=IOT1706B;Integrated Security=True"))
{
foreach (DataRow item in dt.Rows)
{
n += conn.Execute($"insert into Student values(‘{item["姓名"]}‘,‘{(item["性别"].ToString() == "男" ? true : false)}‘,‘{item["爱好"]}‘)");
}
}
if (n > 0)
{
MessageBox.Show("成功导入" + n + "条数据");
Form1_Load(null, null);
}
}
}
}
}

以上是关于WinForm导入导出的主要内容,如果未能解决你的问题,请参考以下文章

winform导入导出excel,后台动态添加控件

各位仁兄,我想请教一下在C#winform中,datagridview如何导出excel文件,将excel导入datagridview.

C#导入导出excel的问题

在winform中怎么导出WPS表格?

C#winform中如何把表导出到EXCEL

我想把WinForm上的内容导出为PDF文档,用C# VS2010 需要引用哪些 dll ,导入哪些命名空间?具体怎么做呢?