导入文件内容到数据库
2016-02-29 18:24
288 查看
此篇文章主要介绍导入Excel,XML和Sql文件到数据库中,重点部分在读取这些文件。
<span style="font-family:KaiTi_GB2312;font-size:24px;color:#330033;"> private void btnInputExcel_Click(object sender, RoutedEventArgs e)
{
//方法一:直接写路径
//InFilePath = "H:\\Demo\\工作\\WpfInput导入文件\\WpfInput\\bin\\Debug\\InputExcel.xlsx";
//方法二:设置文件的属性,让文件生成在主程序的bin文件下
InFilePath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "InputExcel.xls");
//调用方法,将excel导入到Datatable中
DataTable dtInputExcel = ExportToDatatable(InFilePath, 0);
//DataTable dtInputExcel = ExportToDatatableNOPI(InFilePath,0);
//将datatable写入到数据库中
#region //方法一:循环datatable,写入数据库
SqlConnection conn = new SqlConnection(strConn);//连接数据库
conn.Open();
SqlTransaction trans = conn.BeginTransaction();//事物对象
try
{
SqlCommand com = new SqlCommand();//数据操作对象
com.Connection = conn;//指定连接
com.Transaction = trans;//指定事物
//拼接sql语句
StringBuilder sbSql = new StringBuilder();
sbSql.Append("INSERT INTO Users(userID,userName,password) values (");
//对datatable循环
for (int i = 0; i < dtInputExcel.Rows.Count; i++)
{
sbSql.Append("'"+dtInputExcel.Rows[i]["用户ID"].ToString() + "','" + dtInputExcel.Rows[i]["用户名"].ToString() + "','" + dtInputExcel.Rows[i]["密码"].ToString() + "')");
//sql = "INSERT INTO Users(userID,userName,password) values ('" + dtInputExcel.Rows[i]["用户ID"].ToString() + "','" + dtInputExcel.Rows[i]["用户名"].ToString() + "','" + dtInputExcel.Rows[i]["密码"].ToString() + "')";//某一行的数据
if (i < dtInputExcel.Rows.Count-1)
{
sbSql.Append(",(");
}
}
com.CommandText = sbSql.ToString();
com.ExecuteNonQuery();//执行该行
trans.Commit();//如果全部执行完毕.提交
MessageBox.Show("导入Excel成功!", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
}
catch
{
trans.Rollback();//如果有异常.回滚.
}
finally
{
conn.Close();//关闭连接
}
#endregion
//方法二:使用SqlBulkCopy,写入数据库,参考文章:http://blog.csdn.net/shiqijiamengjie/article/details/50587866
}</span>
将文件属性,“复制到输出目录”设置成“始终复制”,“生成操作”设置成“无”,就可以将文件生成到主程序的bin\Debug文件下。如图:
<span style="font-family:KaiTi_GB2312;font-size:24px;color:#330033;">/// <summary>
/// 将Excel文件导入到Datatable中,此处引用GemBox.Spreadsheet,另此葡萄城控件是收费的
/// </summary>
/// <param name="filePath">文件路径</param>
/// <param name="sheetIndex">sheet的索引</param>
/// <returns>datatable</returns>
public static DataTable ExportToDatatable(string filePath, int sheetIndex)
{
ExcelFile ef = ExcelFile.Load(filePath);
if (sheetIndex >= ef.Worksheets.Count)
{
sheetIndex = 0;
}
ExcelWorksheet ws = ef.Worksheets[sheetIndex];
var option = new CreateDataTableOptions()
{
ColumnHeaders = true,
StartRow = 0,
NumberOfRows = ws.Rows.Count,
NumberOfColumns = ws.CalculateMaxUsedColumns(),
Resolution = ColumnTypeResolution.AutoPreferStringCurrentCulture
};
return ws.CreateDataTable(option);
}</span> 使用NPOI读取Excel文件到DataTable中,是转载自:NPOI导入导出Excel操作。大致一样,略有不同。
,不再赘述。
using (StreamReader sr = new StreamReader(item.OpenRead()))
{
strLine = sr.ReadLine();
}
<?xml version="1.0" encoding="GB2312"?>
<NewDataSet>
<Users>
<userID>1</userID>
<userName>丽丽</userName>
<password>1</password>
</Users>
<Users>
<userID>2</userID>
<userName>张三</userName>
<password>2</password>
</Users>
<Users>
<userID>3</userID>
<userName>王五</userName>
<password>3</password>
</Users>
<Users>
<userID>4</userID>
<userName>萌萌</userName>
<password>4</password>
</Users>
</NewDataSet>
<span style="font-family:KaiTi_GB2312;color:#330033;"><span style="background-color: rgb(255, 255, 255); color: rgb(0, 0, 0); font-size: 14px; font-style: normal; font-variant: normal; letter-spacing: normal; line-height: 21px; text-align: left; text-indent: 0px; text-transform: none; white-space: normal; word-spacing: 0px;"></span></span>
<span style="font-family:KaiTi_GB2312;color:#330033;"><span style="background-color: rgb(255, 255, 255); color: rgb(0, 0, 0); font-size: 14px; font-style: normal; font-variant: normal; letter-spacing: normal; line-height: 21px; text-align: left; text-indent: 0px; text-transform: none; white-space: normal; word-spacing: 0px;"></span></span>
<?xml version="1.0" encoding="GB2312"?>这句话很重要,若没有它,xml将无法编码汉字。
方法一:读取xml使用的是XmlDocument。
方法二:读取xml所有内容到DataSet中,参考:SqlBulkCopy批量插入数据
,不再赘述。
ds.ReadXml(item.FullName); //item.FullName是xml文件的全路径和名称
导入excel文件
导入Excel文件分为两步,第一步是将读取Excel文件中的内容到DataTable中;第二步是写入数据库中,可以直接循环DataTable写入数据库中,也可以使用SqlBulkCopy。<span style="font-family:KaiTi_GB2312;font-size:24px;color:#330033;"> private void btnInputExcel_Click(object sender, RoutedEventArgs e)
{
//方法一:直接写路径
//InFilePath = "H:\\Demo\\工作\\WpfInput导入文件\\WpfInput\\bin\\Debug\\InputExcel.xlsx";
//方法二:设置文件的属性,让文件生成在主程序的bin文件下
InFilePath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "InputExcel.xls");
//调用方法,将excel导入到Datatable中
DataTable dtInputExcel = ExportToDatatable(InFilePath, 0);
//DataTable dtInputExcel = ExportToDatatableNOPI(InFilePath,0);
//将datatable写入到数据库中
#region //方法一:循环datatable,写入数据库
SqlConnection conn = new SqlConnection(strConn);//连接数据库
conn.Open();
SqlTransaction trans = conn.BeginTransaction();//事物对象
try
{
SqlCommand com = new SqlCommand();//数据操作对象
com.Connection = conn;//指定连接
com.Transaction = trans;//指定事物
//拼接sql语句
StringBuilder sbSql = new StringBuilder();
sbSql.Append("INSERT INTO Users(userID,userName,password) values (");
//对datatable循环
for (int i = 0; i < dtInputExcel.Rows.Count; i++)
{
sbSql.Append("'"+dtInputExcel.Rows[i]["用户ID"].ToString() + "','" + dtInputExcel.Rows[i]["用户名"].ToString() + "','" + dtInputExcel.Rows[i]["密码"].ToString() + "')");
//sql = "INSERT INTO Users(userID,userName,password) values ('" + dtInputExcel.Rows[i]["用户ID"].ToString() + "','" + dtInputExcel.Rows[i]["用户名"].ToString() + "','" + dtInputExcel.Rows[i]["密码"].ToString() + "')";//某一行的数据
if (i < dtInputExcel.Rows.Count-1)
{
sbSql.Append(",(");
}
}
com.CommandText = sbSql.ToString();
com.ExecuteNonQuery();//执行该行
trans.Commit();//如果全部执行完毕.提交
MessageBox.Show("导入Excel成功!", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
}
catch
{
trans.Rollback();//如果有异常.回滚.
}
finally
{
conn.Close();//关闭连接
}
#endregion
//方法二:使用SqlBulkCopy,写入数据库,参考文章:http://blog.csdn.net/shiqijiamengjie/article/details/50587866
}</span>
将文件属性,“复制到输出目录”设置成“始终复制”,“生成操作”设置成“无”,就可以将文件生成到主程序的bin\Debug文件下。如图:
<span style="font-family:KaiTi_GB2312;font-size:24px;color:#330033;">/// <summary>
/// 将Excel文件导入到Datatable中,此处引用GemBox.Spreadsheet,另此葡萄城控件是收费的
/// </summary>
/// <param name="filePath">文件路径</param>
/// <param name="sheetIndex">sheet的索引</param>
/// <returns>datatable</returns>
public static DataTable ExportToDatatable(string filePath, int sheetIndex)
{
ExcelFile ef = ExcelFile.Load(filePath);
if (sheetIndex >= ef.Worksheets.Count)
{
sheetIndex = 0;
}
ExcelWorksheet ws = ef.Worksheets[sheetIndex];
var option = new CreateDataTableOptions()
{
ColumnHeaders = true,
StartRow = 0,
NumberOfRows = ws.Rows.Count,
NumberOfColumns = ws.CalculateMaxUsedColumns(),
Resolution = ColumnTypeResolution.AutoPreferStringCurrentCulture
};
return ws.CreateDataTable(option);
}</span> 使用NPOI读取Excel文件到DataTable中,是转载自:NPOI导入导出Excel操作。大致一样,略有不同。
<span style="font-family:KaiTi_GB2312;font-size:24px;color:#330033;">/// <summary> /// Excel文件导成Datatable,此处需要引用NPOI /// </summary> /// <param name="strFilePath">Excel文件目录地址</param> /// <param name="strTableName">Datatable表名</param> /// <param name="iSheetIndex">Excel sheet index</param> /// <returns></returns> public static DataTable ExportToDatatableNOPI(string strFilePath, int iSheetIndex) { string strExtName =System.IO.Path.GetExtension(strFilePath); DataTable dt = new DataTable(); if (strExtName.Equals(".xls") || strExtName.Equals(".xlsx")) { using (FileStream file = new FileStream(strFilePath, FileMode.Open, FileAccess.Read)) { HSSFWorkbook workbook = new HSSFWorkbook(file); ISheet sheet = workbook.GetSheetAt(iSheetIndex); //列头 foreach (ICell item in sheet.GetRow(sheet.FirstRowNum).Cells) { dt.Columns.Add(item.ToString(), typeof(string)); } //写入内容 System.Collections.IEnumerator rows = sheet.GetRowEnumerator(); while (rows.MoveNext()) { IRow row = (HSSFRow)rows.Current; if (row.RowNum == sheet.FirstRowNum) { continue; } DataRow dr = dt.NewRow(); foreach (ICell item in row.Cells) { switch (item.CellType) { case CellType.Boolean: dr[item.ColumnIndex] = item.BooleanCellValue; break; case CellType.Error: dr[item.ColumnIndex] = ErrorEval.GetText(item.ErrorCellValue); break; case CellType.Formula: switch (item.CachedFormulaResultType) { case CellType.Boolean: dr[item.ColumnIndex] = item.BooleanCellValue; break; case CellType.Error: dr[item.ColumnIndex] = ErrorEval.GetText(item.ErrorCellValue); break; case CellType.Numeric: if (DateUtil.IsCellDateFormatted(item)) { dr[item.ColumnIndex] = item.DateCellValue.ToString("yyyy-MM-dd hh:MM:ss"); } else { dr[item.ColumnIndex] = item.NumericCellValue; } break; case CellType.String: string str = item.StringCellValue; if (!string.IsNullOrEmpty(str)) { dr[item.ColumnIndex] = str.ToString(); } else { dr[item.ColumnIndex] = null; } break; case CellType.Unknown: case CellType.Blank: default: dr[item.ColumnIndex] = string.Empty; break; } break; case CellType.Numeric: if (DateUtil.IsCellDateFormatted(item)) { dr[item.ColumnIndex] = item.DateCellValue.ToString("yyyy-MM-dd hh:MM:ss"); } else { dr[item.ColumnIndex] = item.NumericCellValue; } break; case CellType.String: string strValue = item.StringCellValue; if (string.IsNullOrEmpty(strValue)) { dr[item.ColumnIndex] = null; } else { dr[item.ColumnIndex] =strValue.ToString(); } break; case CellType.Unknown: case CellType.Blank: default: dr[item.ColumnIndex] = string.Empty; break; } } dt.Rows.Add(dr); } } } return dt; }</span>
导入Sql文件
参考:SqlBulkCopy批量插入数据,不再赘述。
using (StreamReader sr = new StreamReader(item.OpenRead()))
{
strLine = sr.ReadLine();
}
导入XML文件
XML:<?xml version="1.0" encoding="GB2312"?>
<NewDataSet>
<Users>
<userID>1</userID>
<userName>丽丽</userName>
<password>1</password>
</Users>
<Users>
<userID>2</userID>
<userName>张三</userName>
<password>2</password>
</Users>
<Users>
<userID>3</userID>
<userName>王五</userName>
<password>3</password>
</Users>
<Users>
<userID>4</userID>
<userName>萌萌</userName>
<password>4</password>
</Users>
</NewDataSet>
<span style="font-family:KaiTi_GB2312;color:#330033;"><span style="background-color: rgb(255, 255, 255); color: rgb(0, 0, 0); font-size: 14px; font-style: normal; font-variant: normal; letter-spacing: normal; line-height: 21px; text-align: left; text-indent: 0px; text-transform: none; white-space: normal; word-spacing: 0px;"></span></span>
<span style="font-family:KaiTi_GB2312;color:#330033;"><span style="background-color: rgb(255, 255, 255); color: rgb(0, 0, 0); font-size: 14px; font-style: normal; font-variant: normal; letter-spacing: normal; line-height: 21px; text-align: left; text-indent: 0px; text-transform: none; white-space: normal; word-spacing: 0px;"></span></span>
<?xml version="1.0" encoding="GB2312"?>这句话很重要,若没有它,xml将无法编码汉字。
方法一:读取xml使用的是XmlDocument。
<span style="font-family:KaiTi_GB2312;font-size:24px;color:#330033;"> private void btnInputXml_Click(object sender, RoutedEventArgs e) { XmlDocument doc = new XmlDocument(); InFilePath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "InputXML.xml"); doc.Load(InFilePath); XmlElement root = doc.DocumentElement; //获取根节点 XmlNodeList userNodes = root.GetElementsByTagName("Users"); //获取person子节点集合 foreach (XmlNode node in userNodes) { XmlNodeList userId = ((XmlElement)node).GetElementsByTagName("userID"); //获取age子XmlElement集合 if (userId.Count == 1) { string strAge = userId[0].InnerText; } } //读取到xml文件中的内容之后,组合成sql语句,插入到数据库即可。比较简单,不再赘述! } </span>
方法二:读取xml所有内容到DataSet中,参考:SqlBulkCopy批量插入数据
,不再赘述。
ds.ReadXml(item.FullName); //item.FullName是xml文件的全路径和名称
相关文章推荐
- c#调用COM组件
- C#实现把指定数据写入串口
- C#动态创建button的方法
- C#中抽象方法与虚拟方法的区别
- c#中虚函数的相关使用方法
- C#实现给图片加水印的方法
- C#使用加边法计算行列式的值
- C#实现多线程的同步方法实例分析
- C#中尾递归的使用、优化及编译器优化
- C#中的delegate委托类型基本学习教程
- C#实现子窗体与父窗体通信方法实例总结
- C#通用邮件发送类分享
- 举例讲解C#中自动实现的属性
- C#中this的用法集锦
- C#数据结构之顺序表(SeqList)实例详解
- C#.NET获取拨号连接的宽带连接方法
- C#异步绑定数据实现方法
- C#实现AddRange为数组添加多个元素的方法
- C#中Equality和Identity浅析
- C#比较二个数组并找出相同或不同元素的方法