在数据库应用开发中,经常会需要到Excel中的数据直接导入到SQL数据库中;另外为了方便对数据库中的数据进行打印。有时候需要导出数据库中的数据到Excel中,借助Excel自身的打印功能进行报表打印。
窗体控件:4个Button,1个DataGridView,1个对话框OpenFileDialog
1、导入文件功能
添加对话框控件选中要导入的Excel文件
///
/// 导入文件
///
///
///
private void tsbInput_Click(object sender, EventArgs e)
{
string fileName = "";
//选中导入的文件
try
{
//openFileDialog1.Filter = "Excel 文件|*.xls";//指定存放文件格式类型
openFileDialog1.ShowDialog();
fileName = openFileDialog1.FileName.ToString();
}catch(Exception ee)
{
MessageBox.Show("打开文件出错!"+ee.Message.ToString());
}
try
{
if (fileName != "")
{
DuoGonNen d = new dataset();
DataSet ds = d.ds(fileName);//导入文件存放到数据集
dt = ds.Tables[0];
this.dataGridView.DataSource = ds.Tables[0];
tsbStave.Enabled = true;
}
}
catch (Exception me)
{
MessageBox.Show("导入文件出错或无选择文件导入");
}
}
2、导入文件后保存在数据库中
知识点一:if not exists (select * from sysobjects where id = object_id(‘ShiYan’)) 判断是否存在此表
DataTable dt;
///
/// 保存数据库
///
/// "sender">
/// "e">
private void tsbStave_Click(object sender, EventArgs e)
{
string strcon = "server = PC-20161129KNFV\\SQLCSHARP;uid = sa;pwd = 123456;database = DaoRu_DaoChu";
SqlConnection con = new SqlConnection(strcon);
SqlCommand com = con.CreateCommand();
con.Open();
try
{
/*创建表*/
//数据库总查询不到创建新表
Random ran = new Random();
int r = ran.Next(9999999);
//为了导入的表名不被重复才有随机数创建数据库表名
com.CommandText = "if not exists (select * from sysobjects where id = object_id('ShiYan')) create table ShiYan"+r.ToString()+"( ";
for (int i = 0; i < dt.Columns.Count;i++)
{
com.CommandText += dt.Columns[i].ColumnName + " " + "nvarchar(max),";
}
com.CommandText += ")";
com.ExecuteNonQuery();
/*存储数据*/
com = con.CreateCommand();
com.CommandText = "insert into ShiYan"+r.ToString()+" values(@序号,@姓名,@身份证号码)";
//列名
com.Parameters.Add(new SqlParameter("@序号",SqlDbType.NVarChar));//参数名,参数类型
com.Parameters.Add(new SqlParameter("@姓名",SqlDbType.NVarChar));
com.Parameters.Add(new SqlParameter("@身份证号码",SqlDbType.NVarChar));
//数据
for (int i = 0; i < dt.Rows.Count; i++)
{
com.Parameters[0].Value = dt.Rows[i][0].ToString();
com.Parameters[1].Value = dt.Rows[i][1].ToString();
com.Parameters[2].Value = dt.Rows[i][2].ToString();
com.ExecuteNonQuery();
}
MessageBox.Show("已成功将数据导入到数据库中");
}
catch (Exception ee)
{
MessageBox.Show(ee.Message.ToString());
}
finally
{
con.Close();
}
}
3、导出文件功能
窗体控件:2个Bunnto,1个comboBox
导出Excel前提工作:
3.1、因为本人使用的是Microsoft Office 2013,所以在COM组件中对:
“Microsoft.Office.Interop.Excel”和“Microsoft Office 15.0 Object Library”进行引用。
3.2、代码中命名控件的引用:
“using Microsoft.Office.Interop.Excel;”
“using Microsoft.Office.Core;”
3.3、Excel对象模型
包括了128个不同的对象,从矩形,文本框等简单的对象到透视表、图表等复杂的对象。在这里我只使用四种最常用且最重要的对象。
(1)ApplicationClass对象。表示Excel自身的运行环境
(2)Workbook对象。表示Excel工作簿文件(处于ApplicationClass对象的下层)
(3)Worksheet对象。表示Excel工作表文件
(4)Range对象。读取一个或多个单元格
导出功能代码:
///
/// 导出功能
///
/// "sender">
/// "e">
private void DaoC_Click(object sender, EventArgs e)
{
DuoGonNen DGN = new dataset2();
if(DGN.ds2("select * from" + " " + XuanZeWenJian.Text.ToString()).Tables[0].Rows.Count > 0)
{
DataSet ds = DGN.ds2("select * from" + " " +XuanZeWenJian.Text);
ApplicationClass acExcel = new ApplicationClass();//Excel应用程序对象
Workbook wb;//work工作簿
Worksheet ws;//work工作表
acExcel.Visible = true;
wb = acExcel.Workbooks.Add(true);//新建工作簿对象
ws = (Worksheet)wb.Worksheets[1];//引用工作簿中的第一个工作表
//选择要固定表格中显示内容
ws.Cells[1, 2] = "班级学生名册报表";
ws.Cells[2, 1] = "导出" + XuanZeWenJian.Text + "表";
ws.Cells[3, 1] = "打印日期" + DateTime.Now.ToLongDateString();
//显示列名
int rowindex = 5;
int colindex = 1;
foreach(DataColumn dc in ds.Tables[0].Columns)
{
ws.Cells[rowindex, colindex] = dc.ColumnName.ToString();
colindex++;
}
//设置显示的文本为字符格式,以防长数字出现科学记数法的数字形式
int rowcount = ds.Tables[0].Rows.Count;
int colcount = ds.Tables[0].Columns.Count;
ws.get_Range(ws.Cells[rowindex + 1, 1], ws.Cells[rowcount + rowindex, colcount]).NumberFormatLocal = "@";
//显示数据
foreach(DataRow dr in ds.Tables[0].Rows)
{
rowindex++;
colindex = 1;
foreach(DataColumn dc in ds.Tables[0].Columns)
{
ws.Cells[rowindex, colindex] = dr[dc.ColumnName].ToString();
colindex++;
}
}
//导出文件选择是否删除数据库文件
DialogResult drr = MessageBox.Show("确定删除数据库中的数据吗?", "提示", MessageBoxButtons.YesNo);
DGN = new dataset3();
if(drr == System.Windows.Forms.DialogResult.Yes)
{
DGN.ds3("delete"+" "+XuanZeWenJian.Text);
}
else
{
this.Close();
}
}
else
{
MessageBox.Show("该表没有记录","提示窗体",MessageBoxButtons.OK);
}
}
下面是数据链接部分的代码
代码引用:using System.Data.OleDb;
备注:OleDb可以链接任何一种数据库进行操作,比如(Oracle,SQL Server,ACCESS)
下面代码基本都是数据库链接操作,如果看不懂。那去百度吧。这里就不多做解释了。
public abstract class DuoGonNen
{
public abstract DataSet ds(string fileName);//自定义方法,导入Excel中的数据到数据集中
public abstract DataSet ds1(string sqlselect);//Form2下拉控件数据库搜索(数据库中所有的Table)
public abstract DataSet ds2(string sqlselect);//Form2下拉控件选中的表 (检测是否有内容)
public abstract void ds3(string sqldelete);//删除数据库中的表
}
///
/// 自定义方法,导入Excel中的数据到数据集中
///
public class dataset:DuoGonNen
{
public override DataSet ds(string fileName)
{
/*OleDb可以链接任何一种数据库进行操作,比如(Oracle,SQL Server,ACCESS)*/
string strconn = "Provider = Microsoft.Jet.OLEDB.4.0;Data Source="+fileName+"; Extended Properties = Excel 8.0;";
OleDbConnection oledbcon = new OleDbConnection(strconn);
OleDbDataAdapter oledbda = null;
DataSet ds = null;
oledbcon.Open();
try
{
string strselect = "select 序号,姓名,身份证号码 from [Sheet1$]";
oledbda = new OleDbDataAdapter(strselect,oledbcon);
ds = new DataSet();
oledbda.Fill(ds);
}
catch (Exception e)
{
MessageBox.Show("导入表格格式不正确"+e.Message.ToString());
}
finally
{
oledbcon.Close();
}
return ds;
}
public override DataSet ds1(string sqlselect)
{
throw new NotImplementedException();
}
public override DataSet ds2(string sqlselect)
{
throw new NotImplementedException();
}
public override void ds3(string sqldelete)
{
}
}
///
/// Form2下拉控件数据库搜索(数据库中所有的Table)
///
public class dataset1 : DuoGonNen
{
public override DataSet ds1(string sqlselect)
{
DataSet ds = new DataSet();
SqlConnection conn = new SqlConnection("server = PC-20161129KNFV\\SQLCSHARP;uid = sa;pwd = 123456;database = DaoRu_DaoChu");
SqlDataAdapter da = new SqlDataAdapter(sqlselect,conn);
try
{
conn.Open();
da.Fill(ds);
}
catch (Exception e)
{
MessageBox.Show(e.Message.ToString());
}
finally
{
conn.Close();
}
return ds;
}
public override DataSet ds(string fileName)
{
throw new NotImplementedException();
}
public override DataSet ds2(string sqlselect)
{
throw new NotImplementedException();
}
public override void ds3(string sqldelete)
{
}
}
///
/// Form2下拉控件选中的表 (检测是否有内容)
///
public class dataset2 : DuoGonNen
{
public override DataSet ds2(string sqlselect)
{
DataSet ds = new DataSet();
SqlConnection con = new SqlConnection("server = PC-20161129KNFV\\SQLCSHARP;uid = sa;pwd = 123456;database = DaoRu_DaoChu");
try
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(sqlselect,con);
da.Fill(ds);
}
catch(Exception e)
{
MessageBox.Show(e.Message.ToString());
}
finally
{
con.Close();
}
return ds;
}
public override DataSet ds(string fileName)
{
throw new NotImplementedException();
}
public override DataSet ds1(string sqlselect)
{
throw new NotImplementedException();
}
public override void ds3(string sqldelete)
{
}
}
///
/// 删除数据库中的表
///
public class dataset3 : DuoGonNen
{
public override void ds3(string sqldelete)
{
SqlConnection conn = new SqlConnection("server = PC-20161129KNFV\\SQLCSHARP;uid = sa;pwd = 123456;database = DaoRu_DaoChu");
try
{
conn.Open();
SqlCommand com = new SqlCommand(sqldelete, conn);
com.ExecuteNonQuery();
}
catch (Exception e)
{
MessageBox.Show(e.Message.ToString());
}
finally
{
conn.Close();
}
}
public override DataSet ds(string fileName)
{
throw new NotImplementedException();
}
public override DataSet ds1(string sqlselect)
{
throw new NotImplementedException();
}
public override DataSet ds2(string sqlselect)
{
throw new NotImplementedException();
}
}