读取Excel数据到Table表中
Posted 如果声音记得
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了读取Excel数据到Table表中相关的知识,希望对你有一定的参考价值。
方法一:
try
{
List<DBUtility.CommandInfo> list = new List<DBUtility.CommandInfo>();
string strConn = "Provider=Microsoft.Ace.OleDb.12.0;" + "data source=" + path + ";Extended Properties=‘Excel 12.0; HDR=YES; IMEX=1‘"; //此连接可以操作.xls与.xlsx文件
using (OleDbConnection conn = new OleDbConnection(strConn))
{
conn.Open();
DataTable sheetsName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" }); //得到所有sheet的名字
string SheetName = sheetsName.Rows[0][2].ToString();
string strSQL = string.Format("SELECT * FROM [{0}]", SheetName);
OleDbDataAdapter oda = new OleDbDataAdapter(strSQL, strConn);
DataTable dt = new DataTable();
oda.Fill(dt);
if (dt.Rows.Count > 0)
{
DateTime date = DateTime.Parse(System.DateTime.Now.ToString());
string year = date.ToString("yyyy");
string month = date.ToString("MM");
string proName = dt.Rows[0][1].ToString().Substring(5);
strSQL = "insert into tb_targetcostlist (gcmc,Date,UserID) values(‘" + proName + "‘,‘" + date + "‘,‘" + Session["UserId"] + "‘);select @@identity;";
string proID = DBUtility.DbHelperSQL.GetSingle(strSQL).ToString();
for (int i = 1; i < dt.Rows.Count; i++)
{
DBUtility.CommandInfo item = new DBUtility.CommandInfo();
item.CommandText = "insert into tb_MonthlyCost (Num, ProClassification, ProName, Unit, Quantity, UnitPrice, TotalPrice, MonthPlanCost, MonthActuallyCost_GJ, MonthActuallyCost_JD, MonthProfitAndLoss, TotalPlanCost, TotalActuallyCost_GJ, TotalActuallyCost_JD, ProTotalCost, TotalProfitAndLoss, EvenCost, ContractPrice, ProfitAndLoss, Others, Month,Year,proID)"