假如Excel中的數(shù)據(jù)如下:
數(shù)據(jù)庫建表如下:
其中Id為自增字段:
代碼:
代碼如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.OleDb;
using System.Configuration;
using System.Data.SqlClient;
namespace InExcelOutExcel
{
public partial class ExcelToDB : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
FileSvr fileSvr = new FileSvr();
System.Data.DataTable dt = fileSvr.GetExcelDatatable("C://Users//NewSpring//Desktop//Demo//InExcelOutExcel//InExcelOutExcel//excel//ExcelToDB.xlsx", "mapTable");
fileSvr.InsetData(dt);
}
}
class FileSvr
{
/// <summary>
/// Excel數(shù)據(jù)導(dǎo)入Datable
/// </summary>
/// <param name="fileUrl"></param>
/// <param name="table"></param>
/// <returns></returns>
public System.Data.DataTable GetExcelDatatable(string fileUrl, string table)
{
//office2007之前 僅支持.xls
//const string cmdText = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;IMEX=1';";
//支持.xls和.xlsx,即包括office2010等版本的 HDR=Yes代表第一行是標(biāo)題,不是數(shù)據(jù);
const string cmdText = "Provider=Microsoft.Ace.OleDb.12.0;Data Source={0};Extended Properties='Excel 12.0; HDR=Yes; IMEX=1'";
System.Data.DataTable dt = null;
//建立連接
OleDbConnection conn = new OleDbConnection(string.Format(cmdText, fileUrl));
新聞熱點
疑難解答