c\#Excel 데 이 터 를 데이터베이스 에 가 져 오 는 실현 코드
데이터베이스 작성 표 는 다음 과 같다.
그 중 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 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 , ;
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));
try
{
//
if (conn.State == ConnectionState.Broken || conn.State == ConnectionState.Closed)
{
conn.Open();
}
System.Data.DataTable schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
// Excel Sheet
string sheetName = schemaTable.Rows[0]["TABLE_NAME"].ToString().Trim();
// sheet
string strSql = "select * from [" + sheetName + "]";
OleDbDataAdapter da = new OleDbDataAdapter(strSql, conn);
DataSet ds = new DataSet();
da.Fill(ds, table);
dt = ds.Tables[0];
return dt;
}
catch (Exception exc)
{
throw exc;
}
finally
{
conn.Close();
conn.Dispose();
}
}
/// <summary>
/// System.Data.DataTable
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public int InsetData(System.Data.DataTable dt)
{
int i = 0;
string lng = "";
string lat = "";
string offsetLNG = "";
string offsetLAT = "";
foreach (DataRow dr in dt.Rows)
{
lng = dr["LNG"].ToString().Trim();
lat = dr["LAT"].ToString().Trim();
offsetLNG = dr["OFFSET_LNG"].ToString().Trim();
offsetLAT = dr["OFFSET_LAT"].ToString().Trim();
//sw = string.IsNullOrEmpty(sw) ? "null" : sw;
//kr = string.IsNullOrEmpty(kr) ? "null" : kr;
string strSql = string.Format("Insert into DBToExcel (LNG,LAT,OFFSET_LNG,OFFSET_LAT) Values ('{0}','{1}',{2},{3})", lng, lat, offsetLNG, offsetLAT);
string strConnection = ConfigurationManager.ConnectionStrings["ConnectionStr"].ToString();
SqlConnection sqlConnection = new SqlConnection(strConnection);
try
{
// SqlConnection sqlConnection = new SqlConnection(strConnection);
sqlConnection.Open();
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.CommandText = strSql;
sqlCmd.Connection = sqlConnection;
SqlDataReader sqlDataReader = sqlCmd.ExecuteReader();
i++;
sqlDataReader.Close();
}
catch (Exception ex)
{
throw ex;
}
finally
{
sqlConnection.Close();
}
//if (opdb.ExcSQL(strSql))
// i++;
}
return i;
}
}
}
실행 결과:이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
c# Aspose를 사용하여 파일을 인쇄하는 예최근 winform 인쇄 파일을 연구하려면 워드, excel, ppt, pdf, 그림 등 몇 가지 형식을 지원해야 하기 때문에 관련 소프트웨어 환경에 의존할 수 없습니다. 연구 후 Aspose 세트로 관련 파일을 모...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.