WinForm导入导出
2021-01-19 12:12
标签:lse names window client row byte send too mod using System; private void Form1_Load(object sender, EventArgs e) } DataTable dt = new DataTable("Show"); private void button2_Click(object sender, EventArgs e) int n = 0; WinForm导入导出 标签:lse names window client row byte send too mod 原文地址:https://www.cnblogs.com/ryzryz/p/12159956.html
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();
}
{
using (IDbConnection conn = new SqlConnection("Data Source=.;Initial Catalog=IOT1706B;Integrated Security=True"))
{
List
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
//表头
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
{
{"编号","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("导出成功!");
}
}
}
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "Excel|*.xlsx";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
DataTable dt = NpoiExcelHelper.ImportExcel(openFileDialog.FileName);
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);
}
}
}
}
}