C#做的一个在vs2010中导入Excel表格的功能
一:练习时发现问题 在vs调试的时候一遍一遍输入数据十分的麻烦,数据多的话每调试一次就要输入一次数据,十分的浪费时间,所以做成一个小功能可以将数据直接导入,节省时间。
二:过程 1.插入一个dataGridview 控件
2.插入并设置MenuStrip控件并设置属性
效果图如下:
3.准备一个Excel表格
4.运行程序,,导入vs2010中。
三:程序代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace 凯哥
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
{
}
private void 数据导入ToolStripMenuItem_Click(object sender, EventArgs e)
{
{
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
{
}
private void excel文件ToolStripMenuItem_Click(object sender, EventArgs e)
{
dataGridView1.DataSource = null;
dataGridView1.Rows.Clear();
dataGridView1.Columns.Clear();
OpenFileDialog file = new OpenFileDialog();
file.Filter = "Excel文件|*.xls|Excel文件|*.xlsx";
if (file.ShowDialog() == DialogResult.OK)
{
string fname = file.FileName;
string strSource = @"provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + fname + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";
OleDbConnection conn = new OleDbConnection(strSource);
string sqlstring = @"SELECT * FROM [Sheet1$]";
OleDbDataAdapter adapter = new OleDbDataAdapter(sqlstring, conn);
DataSet da = new DataSet();
adapter.Fill(da);
dataGridView1.DataSource = da.Tables[0];
}
else
{ return; }
}
}
}
{
dataGridView1.DataSource = null;
dataGridView1.Rows.Clear();
dataGridView1.Columns.Clear();
OpenFileDialog file = new OpenFileDialog();
file.Filter = "Excel文件|*.xls|Excel文件|*.xlsx";
if (file.ShowDialog() == DialogResult.OK)
{
string fname = file.FileName;
string strSource = @"provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + fname + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";
OleDbConnection conn = new OleDbConnection(strSource);
string sqlstring = @"SELECT * FROM [Sheet1$]";
OleDbDataAdapter adapter = new OleDbDataAdapter(sqlstring, conn);
DataSet da = new DataSet();
adapter.Fill(da);
dataGridView1.DataSource = da.Tables[0];
}
else
{ return; }
}
}
}
四:运行结果:
原Excel表格
导入后效果:
后续:运行刚开始出现如下截图错误,但被我成功解决
哈哈机智如我