C#实现连接数据库查询,将dgv控件数据导出和导入Excel
前提:
主页面
主页面FOm1的代码
DataTable dt = new DataTable();
dt.Columns.Add("epc");
dt.Columns.Add("crc");
dt.Columns.Add("pc");
dt.Columns.Add("time");
dataGridView1.DataSource = dt;
dataGridView1.Columns[0].Width = 205;
dataGridView1.Columns[1].Width = 200;
dataGridView1.Columns[2].Width = 190;
dataGridView1.Columns[3].Width = 200;
进度条方法代码:
private void SetProgressMessage(int pro, ProgressBar proBar)
{
//如果当前调用方不是创建控件的一方,则需要使用this.Invoke()
//在这里,ProgressBar控件是由主线程创建的,所以子线程要对该控件进行操作
//必须执行this.InvokeRequired进行判断。
if (this.InvokeRequired)
{
DelSetPro setPro = new DelSetPro(SetProgressMessage);
this.Invoke(setPro, new object[] { pro, proBar });
}
else
{
proBar.Value = Convert.ToInt32(pro);
}
}
//调用进度条的主方法
private void SleepForProgressBar01()
{
for (int i = 1; i <= 100; i++)
{
Thread.Sleep(10);
SetProgressMessage(i, progressBar1);
}
//DialogResult dr01 = MessageBox.Show("ProgressBar01 has been finished!");
//if (dr01.Equals(DialogResult.OK))
//{
// SetProgressBarVisi(progressBar1);
//}
}
好了,界面布局代码写好之后就开始写功能代码了
第一步:连接数据,把数据库表的数据放入DGV控件里
1、首先新建一个sqlbase类
public class sqlbase
{
//我这里连接的是Sqlserver数据库(server:数据库服务器名称,database:你要操作的数据库名称,其余的是你的登录名称和密码)
public static string ConnectionStr = "server=Lenovo;database=TEST;uid=sa;pwd=aa1997924";
//这个方法表示可以对数据库进行增删改的操作
public static int ExecuteNonQuery(string sql)
{
int result = 0;
using (SqlConnection con = new SqlConnection(ConnectionStr))
{
if (con.State == ConnectionState.Closed)
{
con.Open();
}
try
{
SqlCommand cmd = new SqlCommand(sql, con);
result = cmd.ExecuteNonQuery();
}
catch
{
result = 0;
}
}
return result;
}
//这个方法是对数据库进行查询
public static DataSet GetDataTableBySql(string sql)
{
//DataTable dt = new DataTable();
DataSet ds = new DataSet();
using (SqlConnection con = new SqlConnection(ConnectionStr))
{
if (con.State == ConnectionState.Closed)
{
con.Open();
}
try
{
SqlDataAdapter sda = new SqlDataAdapter(sql, con);
sda.Fill(ds);
}
catch
{
ds = null;
}
}
return ds;
}
2、双击查询按钮,在事件中写如下代码
string strsql = "select * from test";//查询语句
DataSet data1 = sqlbase.GetDataTableBySql(strsql);
dataGridView1.DataSource = data1.Tables[0];
SleepForProgressBar01();
点击查询按钮:如下显示
第二步:将Excel导入
1、在导入按钮事件中写如下代码:
private void btn_daoru_Click(object sender, EventArgs e)
{
try
{
//获取Excel文件路径和名称
OpenFileDialog odXls = new OpenFileDialog();
//指定相应的打开文档的目录 AppDomain.CurrentDomain.BaseDirectory定位到Debug目录,再根据实际情况进行目录调整
string folderPath = AppDomain.CurrentDomain.BaseDirectory + @"databackup\";
odXls.InitialDirectory = folderPath;
// 设置文件格式
odXls.Filter = "Excel files office2003(*.xls)|*.xls|Excel office2010(*.xlsx)|*.xlsx|All files (*.*)|*.*";
//openFileDialog1.Filter = "图片文件(*.jpg)|*.jpg|(*.JPEG)|*.jpeg|(*.PNG)|*.png";
odXls.FilterIndex = 2;
odXls.RestoreDirectory = true;
if (odXls.ShowDialog() == DialogResult.OK)
{
this.txtFilePath.Text = odXls.FileName;
this.txtFilePath.ReadOnly = true;
string sConnString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source={0};" + "Extended Properties='Excel 8.0;HDR=NO;IMEX=1';", odXls.FileName);
if ((System.IO.Path.GetExtension(txtFilePath.Text.Trim())).ToLower() == ".xls")
{
sConnString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "data source=" + odXls.FileName + ";Extended Properties=Excel 5.0;Persist Security Info=False";
//sConnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + txtFilePath.Text.Trim() + ";Extended Properties=\"Excel 8.0;HDR=" + strHead + ";IMEX=1\"";
}
using (OleDbConnection oleDbConn = new OleDbConnection(sConnString))
{
oleDbConn.Open();
DataTable dt = oleDbConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
//判断是否cmb中已有数据,有则清空
if (cmbtablename.Items.Count > 0)
{
cmbtablename.DataSource = null;
cmbtablename.Items.Clear();
}
//遍历dt的rows得到所有的TABLE_NAME,并Add到cmb中
foreach (DataRow dr in dt.Rows)
{
cmbtablename.Items.Add((String)dr["TABLE_NAME"]);
}
if (cmbtablename.Items.Count > 0)
{
cmbtablename.SelectedIndex = 0;
}
SleepForProgressBar01();
// btnshow_Click();
MessageBox.Show("导入成功");
//加载Excel文件数据按钮
// this.btnshow.Enabled = true;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
2、点击导入后会弹框让你选择文件
3、选择你要导入的Excel文件,显示如下界面,textbox控件会显示文件地址,combox会显示文件的多个分表
第三步、将导入的文档放入DGV控件中
1、新增一个加载方法
private void btnshow_Click()
{
#region 读取相应的表名的Excel文件中数据到当前DataGridview中显示
OleDbConnection ole = null;
OleDbDataAdapter da = null;
DataTable dt = null;
string strConn = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source={0};" + "Extended Properties='Excel 8.0;HDR=NO;IMEX=1';", txtFilePath.Text.Trim());
if ((System.IO.Path.GetExtension(txtFilePath.Text.Trim())).ToLower() == ".xls")
{
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "data source=" + txtFilePath.Text.Trim() + ";Extended Properties=Excel 5.0;Persist Security Info=False";
//sConnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + txtFilePath.Text.Trim() + ";Extended Properties=\"Excel 8.0;HDR=" + strHead + ";IMEX=1\"";
}
string sTableName = cmbtablename.Text.Trim();
string strExcel = "select * from [" + sTableName + "]";
try
{
ole = new OleDbConnection(strConn);
ole.Open();
da = new OleDbDataAdapter(strExcel, ole);
dt = new DataTable();
da.Fill(dt);
this.dataGridView1.DataSource = dt;
//因为生成Excel的时候第一行是标题,所以要做如下操作:
//1.修改DataGridView列头的名字,
//2.数据列表中删除第一行
for (int i = 0; i < dt.Columns.Count; i++)
{
//dgvdata.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
//dgvdata.Columns[i].Name = dt.Columns[i].ColumnName;
dataGridView1.Columns[i].HeaderCell.Value = dt.Rows[0][i].ToString();//c# winform 用代码修改DataGridView列头的名字,设置列名,修改列名
}
//DataGridView删除行
dataGridView1.Rows.Remove(dataGridView1.Rows[0]);//删除第一行
//dgvdata.Rows.Remove(dgvdata.CurrentRow);//删除当前光标所在行
//dgvdata.Rows.Remove(dgvdata.Rows[dgvdata.Rows.Count - 1]);//删除最后一行
//dgvdata.Rows.Clear();//删除所有行
ole.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (ole != null)
ole.Close();
}
#endregion
}
2、在加载按钮事件中调用上面方法即可
3、点击加载按钮,如下显示
注意:这里可以选择,第二个分表进行导入(导入的字段名可以和绑定dgv列名不同,并不限制列的个数)
第四部:导出Excel(将dgv控件的数据表导出Excel文档)
1、 新建方法导出方法
private void ExportExcels(string fileName, DataGridView myDGV)
{
string saveFileName = "";
SaveFileDialog saveDialog = new SaveFileDialog();
saveDialog.DefaultExt = "xls";
saveDialog.Filter = "Excel文件|*.xls";
saveDialog.FileName = fileName;
saveDialog.ShowDialog();
saveFileName = saveDialog.FileName;
if (saveFileName.IndexOf(":") < 0) return; //被点了取消
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
if (xlApp == null)
{
MessageBox.Show("无法创建Excel对象,可能您的机子未安装Excel");
return;
}
Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;
Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];//取得sheet1
//写入标题
for (int i = 0; i < myDGV.ColumnCount; i++)
{
worksheet.Cells[1, i + 1] = myDGV.Columns[i].HeaderText;
}
this.label6.Visible = true;
this.label6.Text = myDGV.Rows.Count.ToString();//总进度
//写入数值
for (int r = 0; r < myDGV.Rows.Count; r++)
{
this.label3.Visible = true;
this.label3.Text = r.ToString();//实时进度
for (int i = 0; i < myDGV.ColumnCount; i++)
{
worksheet.Cells[r + 2, i + 1] = myDGV.Rows[r].Cells[i].Value;
}
System.Windows.Forms.Application.DoEvents();
}
worksheet.Columns.EntireColumn.AutoFit();//列宽自适应
if (saveFileName != "")
{
try
{
workbook.Saved = true;
workbook.SaveCopyAs(saveFileName);
}
catch (Exception ex)
{
MessageBox.Show("导出文件时出错,文件可能正被打开!\n" + ex.Message);
}
}
xlApp.Quit();
GC.Collect();//强行销毁
MessageBox.Show("文件: " + fileName + ".xls 保存成功", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
2、在导出事件写如下代码
private void btnshow_Click(object sender, EventArgs e)
{
if (this.dataGridView1.Rows.Count<=0)
{
MessageBox.Show("当前没有可导出的数据!");
return;
}
string a = "D:" + "\\KKHMD.xls";
ExportExcels(a, dataGridView1);
}
3、单击导出,显示如下,选择保存地址
注意:我这里添加了进度显示:
4、导出成功
好了,至此所有功能以实现
1、连接数据库,将数据绑定到的dgv控件
2、Excel的导入
3、Excel的导出