winform实现Excel表格导入Sql数据库示例
winform实现Excel表格导入Sql数据库示例,首先要保证的是将要导入数据库的excel表格中的数据和数据库字段相符,excel中不能存在数据表中不存在的字段。获取excel文档完整路径,并将其中的数据生成dataset对象:
private DataSet xsldata(string filepath)
{
string strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepath + ";Extended Properties='Excel 8.0;IMEX=1'";
System.Data.OleDb.OleDbConnection Conn = new System.Data.OleDb.OleDbConnection(strCon);
string strCom = "SELECT * FROM [Sheet1$]";
Conn.Open();
System.Data.OleDb.OleDbDataAdapter myCommand = new System.Data.OleDb.OleDbDataAdapter(strCom, Conn);
DataSet ds = new DataSet();
myCommand.Fill(ds, "[Sheet1$]");
dataGridView1.DataSource = ds.Tables[0];
Conn.Close();
return ds;
}
完成之后把dataset对象导入数据库中,这里说明一下excel的头一行系统会默认为列名,不对其做导入操作,所以最好做个处理,这里我添加了列名。
private void button1_Click(object sender, EventArgs e)
{
if(txtpath.Text=="")
{
MessageBox.Show("请选择要导入的Excel文档!","系统提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
return;
}
string filepath=txtpath.Text;
SqlConnection conn =new SqlConnection(strcon);//链接数据库
conn.Open();
try
{
DataSet ds = new DataSet();
//取得数据集
//调用上面的函数
ds = xsldata(filepath);
//dataGridView2.DataSource = ds.Tables[0];
int errorcount = 0;//记录错误信息条数
int insertcount = 0;//记录插入成功条数
int updatecount = 0;//记录更新信息条数
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
int cardtypeid = Convert.ToInt32(ds.Tables[0].Rows[i][0].ToString());
string cardnum = ds.Tables[0].Rows[i][1].ToString();
string cardpwd = ds.Tables[0].Rows[i][2].ToString();
int officeid = Convert.ToInt32(ds.Tables[0].Rows[i][3].ToString());
DateTime stdt = Convert.ToDateTime(ds.Tables[0].Rows[i][4].ToString());
string cardstate= ds.Tables[0].Rows[i][5].ToString();
int userid=Convert.ToInt32(ds.Tables[0].Rows[i][6].ToString());
if (cardtypeid != 0 && cardnum != "" && cardpwd != "" && userid != 0 )
{
SqlCommand selectcmd = new SqlCommand("select count(*) from cardsinfo where CardNum='" + cardnum + "'and CardPwd='" + cardpwd + "' and CardState='1' and TypeID="+cardtypeid, conn);
int count = Convert.ToInt32(selectcmd.ExecuteScalar());
if (count > 0)
{
updatecount++;
}
else
{
SqlCommand insertcmd= new SqlCommand("insert into cardsinfo(TypeID,CardNum,CardPwd,OutByOffID,CardTime,CardState,CardByUser) values(" + cardtypeid + ",'" +
cardnum + "','" + cardpwd + "'," + officeid + ",'" + stdt+ "','1',"+userid+")", conn);
insertcmd.ExecuteNonQuery();
insertcount++;
}
}
else
{
//MessageBox.Show("电子表格信息有错!");
errorcount++;
;
}
}
MessageBox.Show( insertcount + "条数据导入成功!" + updatecount + "条数据重复!" + errorcount + "条数据部分信息为空没有导入!");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
这样简单的excel电子表格导入数据库就完成了
WinForm下DataGridView导出Excel实现方法
1.说明:导出的效率说不上很高,但至少是可以接收的.参考网上很多高效导出Excel的方法,实现到时能够实现的,导出速度也很快,不过缺陷在与 不能很好的进行单元格的格式化,比如上图中的"拼音码"字段中的值"000000000012120",在导出后就显示"12120",挺郁闷 的!o(∩_∩)o,废话不说了,进入正题.......
2.首先添加Excel引用
3.实现代码
/// <summary>
/// DataGridView导出Excel
/// </summary>
/// <param name="strCaption">Excel文件中的标题</param>
/// <param name="myDGV">DataGridView 控件</param>
/// <returns>0:成功;1ataGridView中无记录;2:Excel无法启动;9999:异常错 误</returns>
private int ExportExcel(string strCaption, DataGridView myDGV)
{
int result = 9999;
// 列索引,行索引,总列数,总行数
int ColIndex = 0;
int RowIndex = 0;
int ColCount = myDGV.ColumnCount;
int RowCount = myDGV.RowCount;
if (myDGV.RowCount == 0)
{
result = 1;
}
// 创建Excel对象
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
if (xlApp == null)
{
result = 2;
}
try
{
// 创建Excel工作薄
Microsoft.Office.Interop.Excel.Workbook xlBook = xlApp.Workbooks.Add(true);
Microsoft.Office.Interop.Excel.Worksheet xlSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlBook.Worksheets[1];
// 设置标题
Microsoft.Office.Interop.Excel.Range range = xlSheet.get_Range(xlApp.Cells[1, 1], xlApp.Cells[1, ColCount]); //标题所占的单元格数与DataGridView中的列数相同
range.MergeCells = true;
xlApp.ActiveCell.FormulaR1C1 = strCaption;
xlApp.ActiveCell.Font.Size = 20;
xlApp.ActiveCell.Font.Bold = true;
xlApp.ActiveCell.HorizontalAlignment = Microsoft.Office.Interop.Excel.Constants.xlCenter;
// 创建缓存数据
object[,] objData = new object[RowCount + 1, ColCount];
//获取列标题
foreach (DataGridViewColumn col in myDGV.Columns)
{
objData[RowIndex, ColIndex++] = col.HeaderText;
}
// 获取数据
for (RowIndex = 1; RowIndex < RowCount; RowIndex++)
{
for (ColIndex = 0; ColIndex < ColCount; ColIndex++)
{
if (myDGV[ColIndex, RowIndex - 1].ValueType == typeof(string)
|| myDGV[ColIndex, RowIndex - 1].ValueType == typeof(DateTime))//这里就是验证DataGridView单元格中的类型,如果是string或是DataTime类型,则在放入缓 存时在该内容前加入" ";
{
objData[RowIndex, ColIndex] = "" + myDGV[ColIndex, RowIndex - 1].Value;
}
else
{
objData[RowIndex, ColIndex] = myDGV[ColIndex, RowIndex - 1].Value;
}
}
System.Windows.Forms.Application.DoEvents();
}
// 写入Excel
range = xlSheet.get_Range(xlApp.Cells[2, 1], xlApp.Cells[RowCount, ColCount]);
range.Value2 = objData;
//保存
xlBook.Saved = true;
xlBook.SaveCopyAs("C:\\测试" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls");
//返回值
result = 0;
}
catch (Exception err)
{
result = 9999;
}
finally
{
xlApp.Quit();
GC.Collect(); //强制回收
}
return result;
}
4.调用方法(上图中"生成Excel文件"按钮的on
Click事件)
private void button4_Click(object sender, EventArgs e)
{
int result = this.ExportExcel("测试", this.dataGridView1); //this.dataGridView1ataGridView控件
MessageBox.Show(result.ToString());
}