当前位置:网站首页>Several methods of importing excel file data by C #
Several methods of importing excel file data by C #
2022-07-28 17:21:00 【mojocube】
Method 1 : utilize OleDb Direct connection Excel File to read data .
// obtain Excel route
string fileUrl = GetExcel(fuImportStudent);
// Suitable for the old version xls file
const string cmdText = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1;\"";
// Suitable for new version xlsx file
//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;
// Establishing a connection
OleDbConnection connOleDb = new OleDbConnection(string.Format(cmdText, fileUrl));
// Open the connection
if (connOleDb.State == ConnectionState.Broken || connOleDb.State == ConnectionState.Closed)
{
connOleDb.Open();
}
System.Data.DataTable schemaTable = connOleDb.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
// obtain Excel One of the first Sheet name
string sheetName = schemaTable.Rows[0]["TABLE_NAME"].ToString().Trim();
// Inquire about sheet Data in
string strSql = "select * from [" + sheetName + "]";
OleDbDataAdapter da = new OleDbDataAdapter(strSql, connOleDb);
DataSet ds = new DataSet();
da.Fill(ds);
// take Excel The data is translated into DataTable
dt = ds.Tables[0];
// Close the connection
connOleDb.Close();
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
// Write to the database here
// get data :dt.Rows[i][" Header name "].ToString()
}
}If it is to use Microsoft.Jet.OLEDB.4.0 Connected , Need to set up IIS allow 32 Bit program :


advantage : Suitable for simple fixed format Excel form , As long as the header name is on the top , Don't worry about the order .
shortcoming : If read directly MyXls Derived Excel There will be a problem that only the first column can be read ( Edit again or save as xls It can also solve this problem ).
Method 2 : utilize MyXls Read Excel data .
// obtain Excel route
string fileUrl = GetExcel(fuImportContact);
// Load the to be imported Excel
XlsDocument xls = new XlsDocument(fileUrl);
// get Excel Specify a work page in
Worksheet sheet = xls.Workbook.Worksheets[0];
// Reading data Cycle every sheet Every line of the work page , Before not reading 1 That's ok
for (int i = 2; i < sheet.Rows.Count; i++)
{
// Write to the database here
// get data :sheet.Rows[ushort.Parse(i.ToString())].GetCell(1).Value.ToString()
}advantage : Not server dependent , Can read MyXls Derived Excel file .
shortcoming : Must follow Excel Get field data in the order of columns , Strict requirements for time format , The date in numeric format will appear , It needs to be changed . If the data of the column is empty, it may also cause that the column cannot be read , It's not stable .
Method 3 : call Microsoft.Office.Interop.Excel Component read Excel data .
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook workbook;
Microsoft.Office.Interop.Excel.Worksheet worksheet;
object oMissing = System.Reflection.Missing.Value;// Quite a null
workbook = excel.Workbooks.Open(filename, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);
worksheet = (Worksheet)workbook.Worksheets[1];
//int rowCount = int.Parse(txtRow1.Text.Trim()) + 1;// worksheet.UsedRange.Rows.Count;
int colCount = worksheet.UsedRange.Columns.Count;
Microsoft.Office.Interop.Excel.Range range1;
System.Data.DataTable dt = new System.Data.DataTable();
for (int i = 0; i < colCount; i++)
{
range1 = worksheet.Range[worksheet.Cells[1, i + 1], worksheet.Cells[1, i + 1]];
if (range1.Value2 != null)
{
dt.Columns.Add(range1.Value2.ToString());
}
}
for (int j = 1; j < rowCount; j++)
{
SetCount(j, label);
DataRow dr = dt.NewRow();
for (int i = 0; i < colCount; i++)
{
range1 = worksheet.Range[worksheet.Cells[j + 1, i + 1], worksheet.Cells[j + 1, i + 1]];
if (range1.Value2 != null)
{
dr[i] = range1.Value2.ToString();
}
}
dt.Rows.Add(dr);
}
excel.Quit();
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
// Write to the database here
// get data :dt.Rows[i][" Header name "].ToString()
}
}advantage : Can read complex Excel Tabular data , Read columns regardless of order .
shortcoming : Rely on server components , The server needs to be installed Excel Components .
If the time field becomes a number , Such as :

It needs to be changed :
private string ToDateTimeValue(string strNumber)
{
if (!string.IsNullOrWhiteSpace(strNumber))
{
Decimal tempValue;
// First check Is it a number ;
if (Decimal.TryParse(strNumber, out tempValue))
{
// Days , integer
int day = Convert.ToInt32(Math.Truncate(tempValue));
// I don't know why . If it's less than 32, Then subtract 1, Otherwise, decrease 2
// Date from 1900-01-01 Start accumulating
// day = day < 32 ? day - 1 : day - 2;
DateTime dt = new DateTime(1900, 1, 1).AddDays(day < 32 ? (day - 1) : (day - 2));
// Hours : Subtract days , This number converts hours :(* 24)
Decimal hourTemp = (tempValue - day) * 24;// Get hours
// integer . Hours
int hour = Convert.ToInt32(Math.Truncate(hourTemp));
// minute : Lose hours ,( * 60)
// Round here , Otherwise, the value will have 1 Minute error .
Decimal minuteTemp = Math.Round((hourTemp - hour) * 60, 2);// Get minutes
int minute = Convert.ToInt32(Math.Truncate(minuteTemp));
// second : Lose minutes ,( * 60)
// Round here , Otherwise, the value will have 1 Second error .
Decimal secondTemp = Math.Round((minuteTemp - minute) * 60, 2);// Get seconds
int second = Convert.ToInt32(Math.Truncate(secondTemp));
// Time format :00:00:00
string resultTimes = string.Format("{0}:{1}:{2}",
(hour < 10 ? ("0" + hour) : hour.ToString()),
(minute < 10 ? ("0" + minute) : minute.ToString()),
(second < 10 ? ("0" + second) : second.ToString()));
if (day > 0)
return string.Format("{0} {1}", dt.ToString("yyyy-MM-dd"), resultTimes);
else
return resultTimes;
}
}
return string.Empty;
}
边栏推荐
- 线性代数及矩阵论(八)
- Pytorch Foundation: similarities and differences between torch.mul, torch.mm and torch.matmul
- Janus series article 3 API usage guide videoroom creating a new video room
- Some attention code explanations
- Unity shader cartoon style rendering
- GEAR: Graph-based Evidence Aggregating and Reasoning for Fact Verification
- Unity shader transparent effect
- Differences between CNSA and CASC and CASIC
- 浏览器解码过程分析
- Cf/atc/lc topic score website
猜你喜欢

Realization of reflection and refraction effect in unity shader cube texture

Analysis of browser decoding process

飞马D200S无人机与机载激光雷达在大比例尺DEM建设中的应用

mysql 最大建议行数2000w,靠谱吗?

Classroom attendance system based on QT design (using RDS for MySQL cloud database)

The practice of the beego framework for goweb development: Section V project construction and user registration

Round 1C 2022 - Code jam 2022 b.square (Mathematics, thinking)

高速电路中电容的选型和应用——详解

Unity shader realizes mirror effect with rendered texture

高速电路设计实践——概述
随机推荐
软考回顾总结
线性代数及矩阵论(九)
C#遍历集合
UNIQUE VISION Programming Contest 2022(AtCoder Beginner Contest 248)G. GCD cost on the tree
The practice of beego framework developed by goweb: Section 4 database configuration and connection
Use of influxdb2
Some notes on how unity objects move
22年多校第三场(F的证明
高速电路设计实践——概述
Unity shader depth of field effect
Valarray Library Learning
DGL Chapter 1 (official tutorial) personal notes
微信小程序现金红包返回“IP地址非你在商户平台设置的可用IP地址”错误终极解决方法
Function接口之andThen
MySQL数据库增删改查(基础操作命令详解)
Proof of the third scene (f) in 22 years
异步电路设计--同步脉冲器原理及例题
Goweb开发之Beego框架实战:第五节 项目搭建及注册用户
Verilog 每日一题 (VL28 加减计数器)
Ugui learning notes (VI) get the information of the clicked UI