700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > C#窗体将DGV控件中数据导入导出Excel表

C#窗体将DGV控件中数据导入导出Excel表

时间:2021-11-11 10:40:58

相关推荐

C#窗体将DGV控件中数据导入导出Excel表

目录

界面图:

效果视频:

一:将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 ponentModel;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;}}}}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。