目录
界面图:
效果视频:
一:将DGV数据导出到Excel表中
二:将Excel表数据导入到DGV中
三:界面全部代码
界面图:
效果视频:
DGV数据导入导出Excel
一:将DGV数据导出到Excel表中
public void dgvtoexcel()
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
saveFileDialog.FilterIndex = 0;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.CreatePrompt = true;
saveFileDialog.Title = "Export Excel File";
saveFileDialog.ShowDialog();
if (saveFileDialog.FileName == "")
return;
Stream myStream;
myStream = saveFileDialog.OpenFile();
StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
string str = "";
try
{
for (int i = 0; i < dataGridView.Columns.Count; i++)
{
if (i > 0)
{
str += "\t";
}
str += dataGridView.Columns[i].HeaderText;
}
sw.WriteLine(str);
for (int j = 0; j < dataGridView.Rows.Count; j++)
{
string tempStr = "";
for (int k = 0; k < dataGridView.Columns.Count; k++)
{
if (k > 0)
{
tempStr += "\t";
}
tempStr += dataGridView.Rows[j].Cells[k].Value.ToString();
}
sw.WriteLine(tempStr);
}
sw.Close();
myStream.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
sw.Close();
myStream.Close();
}
}
二:将Excel表数据导入到DGV中
public void excelstodgv3()
{
/// <summary>
/// 从excel文件读取内容
/// </summary>
/// <param name="fileName">excel文件名</param>
/// <returns>获取读取数据的表</returns>
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Excel Files|*.xlsx;*.xls";
ofd.Title = "选着Excel文件";
if (ofd.ShowDialog() == DialogResult.OK)
{
string fileName = ofd.FileName;//路径名称
Microsoft.Office.Interop.Excel.Application excelApp = null;
Microsoft.Office.Interop.Excel.Workbooks wbks = null;
Microsoft.Office.Interop.Excel._Workbook wbk = null;
try
{
excelApp = new Microsoft.Office.Interop.Excel.Application();
excelApp.Visible = false;//是打开不可见
wbks = excelApp.Workbooks;
wbk = wbks.Add(fileName);
object Nothing = Missing.Value;
Microsoft.Office.Interop.Excel._Worksheet whs;
whs = (Microsoft.Office.Interop.Excel._Worksheet)wbk.Sheets[1];//获取第一张工作表
whs.Activate();
System.Data.DataTable dt = new System.Data.DataTable(whs.Name);
//读取excel表格的列标题
int col_count = whs.UsedRange.Columns.Count;
for (int col = 1; col <= col_count; col++)
{
dt.Columns.Add(((Microsoft.Office.Interop.Excel.Range)whs.Cells[1, col]).Text.ToString());
}
//读取数据
for (int row = 2; row <= whs.UsedRange.Rows.Count; row++)
{
DataRow dr = dt.NewRow();
for (int col = 1; col <= col_count; col++)
{
dr[col - 1] = ((Microsoft.Office.Interop.Excel.Range)whs.Cells[row, col]).Text.ToString();
}
dt.Rows.Add(dr);
}
dataGridView1.DataSource = dt;
}
catch (Exception e)
{
MessageBox.Show("异常:" + e);
}
finally
{
//wbks.Close();//关闭工作簿
excelApp.Quit();//关闭excel应用程序
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);//释放excel进程
excelApp = null;
}
}
}
三:界面全部代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WinCCAndCUserDemoTest
{
public partial class Form6 : Form
{
public Form6()
{
InitializeComponent();
intotwoadd();
}
/// <summary>
/// 初始化twoadd
/// </summary>
public void intotwoadd()
{
//根据Header和所有单元格的内容自动调整行的高度
dataGridView.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
//设置内容对齐方式和字体
dataGridView.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
//dataGridView_Report.Font = new Font("宋体", 10);
//设置所有单元格都不可编辑
dataGridView.ReadOnly = true;
//设置标题头列宽
dataGridView.RowHeadersWidth = 15;
//不可以增加空行
dataGridView.AllowUserToAddRows = false;
//添加表头
for (int i = 0; i < 4; i++)
{
dataGridView.Columns.Add(new DataGridViewTextBoxColumn());
}
//指定标题列宽
dataGridView.Columns[0].Width = 100;
dataGridView.Columns[1].Width = 100;
dataGridView.Columns[2].Width = 100;
dataGridView.Columns[3].Width = 100;
//添加标题字符
dataGridView.Columns[0].HeaderText = "序号";
dataGridView.Columns[1].HeaderText = "姓名";
dataGridView.Columns[2].HeaderText = "性别";
dataGridView.Columns[3].HeaderText = "班级";
}
private void button7_Click(object sender, EventArgs e)
{
//排除异常输入
if (textBox_Name.Text == string.Empty || comboBox_Sex.Text == string.Empty || comboBox_Class.Text == string.Empty)
{
return;
}
//得到总行数
int num = dataGridView.Rows.Count;
//向第一行插入一行数据
this.dataGridView.Rows.Insert(0, 1);
//写第一行第二列数据//插入名字
this.dataGridView.Rows[0].Cells[1].Value = textBox_Name.Text;
//写第一行第三列数据//插入性别
this.dataGridView.Rows[0].Cells[2].Value = comboBox_Sex.Text;
//写第一行第四列数据//插入班级
this.dataGridView.Rows[0].Cells[3].Value = comboBox_Class.Text;
//写第所有行第一列数据//插入显示序号
for (int i = 0; i < num + 1; i++)
{
this.dataGridView.Rows[i].Cells[0].Value = i + 1;
}
//去除选择
dataGridView.ClearSelection();
}
private void button11_Click(object sender, EventArgs e)
{
excelstodgv3();
}
private void button3_Click(object sender, EventArgs e)
{
dgvtoexcel();
}
public void dgvtoexcel()
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
saveFileDialog.FilterIndex = 0;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.CreatePrompt = true;
saveFileDialog.Title = "Export Excel File";
saveFileDialog.ShowDialog();
if (saveFileDialog.FileName == "")
return;
Stream myStream;
myStream = saveFileDialog.OpenFile();
StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
string str = "";
try
{
for (int i = 0; i < dataGridView.Columns.Count; i++)
{
if (i > 0)
{
str += "\t";
}
str += dataGridView.Columns[i].HeaderText;
}
sw.WriteLine(str);
for (int j = 0; j < dataGridView.Rows.Count; j++)
{
string tempStr = "";
for (int k = 0; k < dataGridView.Columns.Count; k++)
{
if (k > 0)
{
tempStr += "\t";
}
tempStr += dataGridView.Rows[j].Cells[k].Value.ToString();
}
sw.WriteLine(tempStr);
}
sw.Close();
myStream.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
sw.Close();
myStream.Close();
}
}
public void excelstodgv3()
{
/// <summary>
/// 从excel文件读取内容
/// </summary>
/// <param name="fileName">excel文件名</param>
/// <returns>获取读取数据的表</returns>
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Excel Files|*.xlsx;*.xls";
ofd.Title = "选着Excel文件";
if (ofd.ShowDialog() == DialogResult.OK)
{
string fileName = ofd.FileName;//路径名称
Microsoft.Office.Interop.Excel.Application excelApp = null;
Microsoft.Office.Interop.Excel.Workbooks wbks = null;
Microsoft.Office.Interop.Excel._Workbook wbk = null;
try
{
excelApp = new Microsoft.Office.Interop.Excel.Application();
excelApp.Visible = false;//是打开不可见
wbks = excelApp.Workbooks;
wbk = wbks.Add(fileName);
object Nothing = Missing.Value;
Microsoft.Office.Interop.Excel._Worksheet whs;
whs = (Microsoft.Office.Interop.Excel._Worksheet)wbk.Sheets[1];//获取第一张工作表
whs.Activate();
System.Data.DataTable dt = new System.Data.DataTable(whs.Name);
//读取excel表格的列标题
int col_count = whs.UsedRange.Columns.Count;
for (int col = 1; col <= col_count; col++)
{
dt.Columns.Add(((Microsoft.Office.Interop.Excel.Range)whs.Cells[1, col]).Text.ToString());
}
//读取数据
for (int row = 2; row <= whs.UsedRange.Rows.Count; row++)
{
DataRow dr = dt.NewRow();
for (int col = 1; col <= col_count; col++)
{
dr[col - 1] = ((Microsoft.Office.Interop.Excel.Range)whs.Cells[row, col]).Text.ToString();
}
dt.Rows.Add(dr);
}
dataGridView1.DataSource = dt;
}
catch (Exception e)
{
MessageBox.Show("异常:" + e);
}
finally
{
//wbks.Close();//关闭工作簿
excelApp.Quit();//关闭excel应用程序
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);//释放excel进程
excelApp = null;
}
}
}
}
}