方法一:

            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表中的更多相关文章

  1. spark读取mongodb数据写入hive表中

    一 环境: spark-: hive-; scala-; hadoop--cdh-; jdk-1.8; mongodb-2.4.10; 二.数据情况: MongoDB数据格式{    "_i ...

  2. SQL语句完成Excel数据导入数据库表中流程方法及注意事项

    第一步:先查看数据库是否安装AccessDatabaseEngine_X64.exe, 如下图查看: 如果未安装先下载脚本之家下载地址 https://www.jb51.net/softs/29150 ...

  3. Python用xlrd读取Excel数据到list中再用xlwt把数据写入到新的Excel中

    一.先用xlrd读取Excel数据到list列表中(存入列表中的数据如下图所示) import xlrd as xd #导入需要的包 import xlwt data =xd.open_workboo ...

  4. Delphi中使用python脚本读取Excel数据

    Delphi中使用python脚本读取Excel数据2007-10-18 17:28:22标签:Delphi Excel python原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 . ...

  5. JAVA反射机制示例,读取excel数据映射到JAVA对象中

    import java.beans.PropertyDescriptor; import java.io.File; import java.io.FileInputStream; import ja ...

  6. java的poi技术读取Excel数据到MySQL

    这篇blog是介绍java中的poi技术读取Excel数据,然后保存到MySQL数据中. 你也可以在 : java的poi技术读取和导入Excel了解到写入Excel的方法信息 使用JXL技术可以在 ...

  7. jxl读写excel, poi读写excel,word, 读取Excel数据到MySQL

    这篇blog是介绍: 1. java中的poi技术读取Excel数据,然后保存到MySQL数据中. 2. jxl读写excel 你也可以在 : java的poi技术读取和导入Excel了解到写入Exc ...

  8. 读取Excel数据到DataTable

    读取Excel数据到DataTable 代码 /// <summary> /// 获取指定路径.指定工作簿名称的Excel数据:取第一个sheet的数据 /// </summary& ...

  9. Python读取Excel数据并根据列名取值

    一直想将自己接触到的东西梳理一遍,可就是迈不出第一步,希望从这篇总结开始不要再做行动的矮人了. 最近测试过程中需要用到python读取excel用例数据,于是去了解和学习了下xlrd库,这里只记录使用 ...

随机推荐

  1. [Android ] linux命令英文缩写的含义(方便记忆)

    du -sh */ reference to : http://blog.chinaunix.net/uid-27164517-id-3299073.html linux常用命令的英文单词缩写 命令缩 ...

  2. ASP.NET SignalR 与 LayIM2.0 配合轻松实现Web聊天室(六) 之 Layim源码改造右键菜单--好友、组管理功能的实现。

    前言 上一篇中讲解了加好友的流程,本篇将介绍好友管理,群组管理的右键菜单功能.当然由于菜单项目太多,都实现也得花费时间.只讲解一下我是如何从不知道怎么实现右键菜单到会自定义菜单的一个过程.另外呢,针对 ...

  3. Linux 查看 删除进程

    这东西,时间久不用总容易忘....记下来! 1. 在 LINUX 命令平台输入 1-2 个字符后按 Tab 键会自动补全后面的部分(前提是要有这个东西,例如在装了 tomcat 的前提下, 输入 to ...

  4. 恶趣味小游戏 I'm hungry

    之前学算法的时候无聊做了个游戏放松放松,现在传到了github以免电脑坏了就永远丢失了... github地址:https://github.com/BenDanChen/IamHungry I am ...

  5. IOS之笑脸app

    ios笑脸app实现 import UIKit @IBDesignable class FaceView: UIView { @IBInspectable var lineWidth:CGFloat= ...

  6. iOS,Objective-C,相册功能的实现。

    #import "ViewController.h" #define kuan [UIScreen mainScreen].bounds.size.width #define ga ...

  7. HTML5学习之跨文档传输消息(七)

    新标准中提供了文档之间直接的消息传输API.而且不限制跨域消息传递! 发送消息使用的是Window对象的postMessage(data,targetURL)方法就可以了,但给哪个window对象发送 ...

  8. Linux Shell 高级编程技巧3----运行级别脚本介绍

    3.运行级别脚本介绍    3.1.运行级别        运行级别介绍:            0    关机            1    单用户模式            2    多用户模式 ...

  9. ERROR 1290 (HY000): The MySQL server is running with the --skip-grant-tables option so it cannot execute this statemen

    转自:http://www.cnblogs.com/iosdev/archive/2013/07/15/3190431.html mysql 配置文件目录:/etc/my.cnf root 密码为空的 ...

  10. 高效jQuery的奥秘

    讨论jQuery和javascript性能的文章并不罕见.然而,本文我计划总结一些速度方面的技巧和我本人的一些建议,来提升你的jQuery和javascript代码.好的代码会带来速度的提升.快速渲染 ...