读取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)";
item.CommandText += "values(";
item.CommandText += "'" + dt.Rows[i][0].ToString() + "','" + dt.Rows[i][1].ToString() + "','" + dt.Rows[i][2].ToString() + "','" + dt.Rows[i][3].ToString() + "','" + dt.Rows[i][4].ToString() + "','" + dt.Rows[i][5].ToString() + "','" + dt.Rows[i][6].ToString() + "','" + dt.Rows[i][7].ToString() + "','" + dt.Rows[i][8] + "','" + dt.Rows[i][9].ToString() + "','" + dt.Rows[i][10].ToString() + "','" + dt.Rows[i][11].ToString() + "','" + dt.Rows[i][12].ToString() + "','" + dt.Rows[i][13].ToString() + "','" + dt.Rows[i][14].ToString() + "','" + dt.Rows[i][15].ToString() + "','" + dt.Rows[i][16].ToString() + "','" + dt.Rows[i][17].ToString() + "','" + dt.Rows[i][18].ToString() + "','" + dt.Rows[i][19].ToString() + "','" + month + "','" + year + "','" + proID + "'";
item.CommandText += ")";
list.Add(item);
DBUtility.DbHelperSQL.ExecuteSqlTran(list);
item.CommandText = "";
}
}
} }
catch (Exception ex)
{
Page.RegisterStartupScript("", "<script>alert('" + ex.Message + "');</script>");
}

方法二:
此方法弊端:每次都会产生一个EXCEL.exe进程,下次再运行,要不这个进程关闭才行,非常不方便

private void ReadExcelToTable(string path)
{
Microsoft.Office.Interop.Excel.Application oXL;
Microsoft.Office.Interop.Excel._Workbook oWB;
Microsoft.Office.Interop.Excel._Worksheet oSheet;
object missing = System.Type.Missing; //创建Excel实例
oXL = new Microsoft.Office.Interop.Excel.Application(); //打开已有的工作簿
oWB = oXL.Workbooks.Open(path, missing, missing, missing, missing, missing, missing,
missing, missing, missing, missing, missing, missing, missing, missing); //导入服务器的连接
String strcon = "Data Source=192.168.1.245;Initial Catalog=Component;User ID=sa;Password=yuxit2008";
using (SqlConnection objcon1 = new SqlConnection(strcon))
{
objcon1.Open(); for (int i = 1; i <= oWB.Sheets.Count; i++)
{
oSheet = (Microsoft.Office.Interop.Excel.Worksheet)oWB.Sheets.get_Item(i);
//tb_targetcostlist中插入标题,项目名称等
DateTime date = DateTime.Parse(System.DateTime.Now.ToString());
string year = date.ToString("yyyy");
string month = date.ToString("MM");
string proName = GetCellText(2, 2, oSheet).Substring(5);
string title = GetCellText(1, 1, oSheet);
string strSQL = "insert into tb_targetcostlist(gcmc,Title,Date,UserID) values('" + proName + "','" + title + "','" + date + "','" + Session["UserId"] + "');select @@identity;";
string proID = DBUtility.DbHelperSQL.GetSingle(strSQL).ToString(); // 从第二行开始遍历 行、列 数据
for (int j = 2; j <= oSheet.UsedRange.Rows.Count; j++)
{
string str = "";
for (int n = 1; n < oSheet.UsedRange.Columns.Count; n++)
{
str += "'" + GetCellText(j, n, oSheet) + "',";
}
string strinsert = @"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,Year,Month,ProID)" +
" values(" + str + "'" + year + "','" + month + "','" + proID + "')"; using (SqlCommand objcom = new SqlCommand(strinsert, objcon1))
{
objcom.ExecuteNonQuery();
} }
}
}
}
///<summary>
///获取单元格文本
///</summary>
///<param name="row"></param>
///<param name="col"></param>
///<param name="oSheet"></param>
///<returns></returns>
private string GetCellText(int row, int col, Microsoft.Office.Interop.Excel._Worksheet oSheet)
{
string result = "";
bool isFound = false;
int rowEnd = 1;
int colEnd = 1; Microsoft.Office.Interop.Excel.Range oRng = (Microsoft.Office.Interop.Excel.Range)oSheet.Cells[row, col];
if (oRng.Value2 != null)
{
result = oRng.Value2.ToString();
isFound = true;
}
else
{
if (!(bool)oRng.MergeCells) // 如果该单元格无值且不是合并的,则返回 null
{
result = null;
isFound = true;
}
}
if (!isFound)
{
// 倒序遍历该列所有行(从倒2行开始),判断是否有合并单元格且有值,如果遇到则已求出,
// 如果遇到非合并单元格,则行+1(倒回1行),列同样倒序进行
for (int r = row - 1; r >= 1; r--)
{
oRng = (Microsoft.Office.Interop.Excel.Range)oSheet.Cells[r, col];
if ((bool)oRng.MergeCells)
{
try
{
if (oRng.Value2 != null)
{
result = oRng.Value2.ToString();
isFound = true;
break;
}
}
catch (Exception)
{ }
}
else
{
rowEnd = r + 1;
break;
}
}
if (!isFound)
{
// 倒序遍历该行所有列,判断是否有合并单元格且有值,如果遇到则已求出,如果遇到非合并单元格,则说明数据非法。。。
for (int c = col - 1; c >= 1; c--)
{
oRng = (Microsoft.Office.Interop.Excel.Range)oSheet.Cells[rowEnd, c];
if ((bool)oRng.MergeCells)
{
try
{
if (oRng.Value2 != null)
{
result = oRng.Value2.ToString();
isFound = true;
break;
}
}
catch (Exception)
{ }
}
else
{
colEnd = c + 1;
break;
}
}
}
if (!isFound)
{
result = null;
}
}
return result;
}

方法三(重点):
使用NPOI读取单元格。对于合并单元格:相同值,读取多次,存储到数据库表中

private void ReadExcelToTable(string path)
{
using (FileStream fs=File.Open(path,FileMode.Open))
{
using (Workbook wk=new HSSFWorkbook(fs))
{
for (int i = 0; i < wk.NumberOfSheets; i++)
{
using (Sheet sheet = wk.GetSheetAt(i))
{
//tb_targetcostlist中插入标题,项目名称等
DateTime date = DateTime.Parse(System.DateTime.Now.ToString());
string year = date.ToString("yyyy");
string month = date.ToString("MM");
Cell cell_title = sheet.GetRow(0).GetCell(0);
Cell cell_proName = sheet.GetRow(1).GetCell(1);
Cell cell_monthly=sheet.GetRow(1).GetCell(9);
Cell cell_total=sheet.GetRow(1).GetCell(13);
string proName = getCellValue(cell_proName).Substring(5);
string title = getCellValue(cell_title);
string monthlyProduct=getCellValue(cell_monthly);
string totalProduct=getCellValue(cell_total);
string strSQL = "insert into tb_targetcostlist(ProName, Title, Date, UserID,MonthlyProduct,TotalProduct) values('" + proName + "','" + title + "','" + date + "','" + Session["UserId"] + "','" + monthlyProduct + "','" + totalProduct + "');select @@identity";
string proID = DBUtility.DbHelperSQL.GetSingle(strSQL).ToString(); //从第3行开始遍历
for (int j = 2; j <= sheet.LastRowNum; j++)
{
string value = "";
Row curRow = sheet.GetRow(j);
if (curRow != null)
{
for (int m = 0; m < 19; m++)
{
Cell cell = curRow.GetCell(m);
if (cell != null)
{
if (isMergedRegion(sheet, j, m))
{
value += "'" + getMergedRegionValue(sheet, j, m) + "',";
}
else
{
value += "'" + getCellValue(cell) + "',";
}
}
else
{
value += "'',";
} } string strinsert = @"insert into tb_MonthlyCost( Num, ProClassification, ItemName, Unit, Quantity, UnitPrice, TotalPrice, MonthPlanCost, MonthActuallyCost_GJ, MonthActuallyCost_JD, MonthProfitAndLoss, TotalPlanCost, TotalActuallyCost_GJ, TotalActuallyCost_JD, ProTotalCost, TotalProfitAndLoss, EvenCost, ContractPrice, ProfitAndLoss,Year,Month,ProID)" +
" values(" + value + "'" + year + "','" + month + "','" + proID + "')"; DBUtility.DbHelperSQL.GetSingle(strinsert);
}
}
}
}
}
}
}
/// <summary>
/// 获取合并单元格的值
/// </summary>
/// <param name="sheet"></param>
/// <param name="row"></param>
/// <param name="column"></param>
/// <returns></returns> public String getMergedRegionValue(Sheet sheet, int row, int column)
{
int sheetMergeCount = sheet.NumMergedRegions; for (int i = 0; i < sheetMergeCount; i++)
{
CellRangeAddress ca = sheet.GetMergedRegion(i);
int firstColumn = ca.FirstColumn;
int lastColumn = ca.LastColumn;
int firstRow = ca.FirstRow;
int lastRow = ca.LastRow; if (row >= firstRow && row <= lastRow)
{ if (column >= firstColumn && column <= lastColumn)
{
Row fRow = sheet.GetRow(firstRow);
Cell fCell = fRow.GetCell(firstColumn); return getCellValue(fCell);
}
}
}
return null;
} /// <summary>
/// 判断指定的单元格是否是合并单元格
/// </summary>
/// <param name="sheet"></param>
/// <param name="row"></param>
/// <param name="column"></param>
/// <returns></returns>
public bool isMergedRegion(Sheet sheet, int row, int column)
{
int sheetMergeCount = sheet.NumMergedRegions; for (int i = 0; i < sheetMergeCount; i++)
{
CellRangeAddress ca = sheet.GetMergedRegion(i);
int firstColumn = ca.FirstColumn;
int lastColumn = ca.LastColumn;
int firstRow = ca.FirstRow;
int lastRow = ca.LastRow; if (row >= firstRow && row <= lastRow)
{
if (column >= firstColumn && column <= lastColumn)
{
return true;
}
}
} return false;
} /// <summary>
/// 获取单元格的值
/// </summary>
/// <param name="cell"></param>
/// <returns></returns>
public String getCellValue(Cell cell)
{ if (cell == null) return ""; if (cell.CellType == CellType.STRING)
{
return cell.StringCellValue;
}
else if (cell.CellType == CellType.BOOLEAN)
{
return cell.BooleanCellValue.ToString();
}
else if (cell.CellType == CellType.FORMULA)
{ //此处注意,对于通过公式计算出来的单元格值,返回值为cell.NumericCellValue.ToString();
return cell.NumericCellValue.ToString();
}
else if (cell.CellType == CellType.NUMERIC)
{
return cell.NumericCellValue.ToString();
}
return "";
读取Excel数据到Table表中的更多相关文章
- spark读取mongodb数据写入hive表中
一 环境: spark-: hive-; scala-; hadoop--cdh-; jdk-1.8; mongodb-2.4.10; 二.数据情况: MongoDB数据格式{ "_i ...
- SQL语句完成Excel数据导入数据库表中流程方法及注意事项
第一步:先查看数据库是否安装AccessDatabaseEngine_X64.exe, 如下图查看: 如果未安装先下载脚本之家下载地址 https://www.jb51.net/softs/29150 ...
- Python用xlrd读取Excel数据到list中再用xlwt把数据写入到新的Excel中
一.先用xlrd读取Excel数据到list列表中(存入列表中的数据如下图所示) import xlrd as xd #导入需要的包 import xlwt data =xd.open_workboo ...
- Delphi中使用python脚本读取Excel数据
Delphi中使用python脚本读取Excel数据2007-10-18 17:28:22标签:Delphi Excel python原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 . ...
- JAVA反射机制示例,读取excel数据映射到JAVA对象中
import java.beans.PropertyDescriptor; import java.io.File; import java.io.FileInputStream; import ja ...
- java的poi技术读取Excel数据到MySQL
这篇blog是介绍java中的poi技术读取Excel数据,然后保存到MySQL数据中. 你也可以在 : java的poi技术读取和导入Excel了解到写入Excel的方法信息 使用JXL技术可以在 ...
- jxl读写excel, poi读写excel,word, 读取Excel数据到MySQL
这篇blog是介绍: 1. java中的poi技术读取Excel数据,然后保存到MySQL数据中. 2. jxl读写excel 你也可以在 : java的poi技术读取和导入Excel了解到写入Exc ...
- 读取Excel数据到DataTable
读取Excel数据到DataTable 代码 /// <summary> /// 获取指定路径.指定工作簿名称的Excel数据:取第一个sheet的数据 /// </summary& ...
- Python读取Excel数据并根据列名取值
一直想将自己接触到的东西梳理一遍,可就是迈不出第一步,希望从这篇总结开始不要再做行动的矮人了. 最近测试过程中需要用到python读取excel用例数据,于是去了解和学习了下xlrd库,这里只记录使用 ...
随机推荐
- 备忘zookeeper(单机+伪集群+集群)
#下载: #单机模式 解压到合适目录. 进入zookeeper目录下的conf子目录, 复制zoo_sample.cfg-->zoo.cfg(如果没有data和logs就新建):tickTime ...
- Mac下java开发环境的搭建与开发工具的安装
一.安装JDK 1.根据你当前环境的需要,下载相应的JDK并安装,安装步骤与其他Mac软件安装方法相同,我安装的是jdk1.8.0_74.jdk,mac中jdk1.8的默认位置:/Library/Ja ...
- hdu 2027统计元音
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2027 思路:主要考察gets()函数用法,能够接受输入的空格,如果用%s或是cin>>st ...
- 谈谈我的编程之路---WAMP(二)
WAMP的一些配置与使用心得(MYSQL) 刚开始接触数据库的时候,我一直认为数据库操作工具和数据库是同一种东西,它们是一体的,后来我才明白,数据库它是一个独立的仓库,用官方点的话来解释 数据库(Da ...
- Python lambda函数使用
- MVC – 6.控制器 Action方法参数与返回值
6.1 Controller接收浏览器数据 a.获取Get数据 : a1:获取路由url中配置好的制定参数: 如配置好的路由: 浏览器请求路径为: /User/Modify/1 ,MVC框架获 ...
- scala的tcp通信
client: object ActorClient extends App { import actors.Actor, actors.remote.Node, actors.remote.Remo ...
- redmine安装部署
http://www.sxt.cn/u/4647/blog/5557 http://blog.chinaunix.net/uid-26729093-id-4669508.html http://my. ...
- android 入门-微博分享
[2015-03-11 13:40:32 - WeiboSDK] Unable to resolve target 'android-8' 修改project.properties target=a ...
- Parallel.js初探
今天闲着看了一下Parallel.js.这个库暂时貌似还没有什么中文的介绍(可能暂时用的人都不多吧).所以就只能上github找它得源码和介绍看看了.貌似它的代码也不多,以后可以深入研究一下. 先简单 ...