方法一:

            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. Hibernate双向多对多对象关系模型映射

    1 双向many-to-many 业务模型: 描述员工和项目 一个员工同时可以参与多个项目 一个项目中可以包含多个员工 分析:数据库的数据模型,通过中间关系表,建立两个one-to-many构成man ...

  2. vector reserve与resize区别

    vector 的reserve增加了vector的capacity,但是它的size没有改变!而resize改变了vector的capacity同时也增加了它的size!原因如下:reserve是容器 ...

  3. mac版的PS和DW破解版安装

    到网上找到破解版的安装文件,一般是一个dmg安装文件,和一个补丁文件,安装的时候,要先断网,然后点击软件,选试用安装,安装完毕后,不要打开软件,直接关闭掉,然后到应用程序里找到软件图标,右击打开包文件 ...

  4. iOS - 线程管理

    iOS开发多线程篇—GCD的常见用法 一.延迟执行 1.介绍 iOS常见的延时执行有2种方式 (1)调用NSObject的方法 [self performSelector:@selector(run) ...

  5. MVC学习笔记---各种上下文context

    0  前言 AspNet MVC中比较重要的上下文,有如下: 核心的上下文有HttpContext(请求上下文),ControllerContext(控制器上下文) 过滤器有关有五个的上下文Actio ...

  6. JustSniffer

    http://blog.csdn.net/cnbird2008/article/details/5875781

  7. 【Java EE 学习 19】【使用过滤器实现全站压缩】【使用ThreadLocal模式解决跨DAO事务回滚问题】

    一.使用过滤器实现全站压缩 1.目标:对网站的所有JSP页面进行页面压缩,减少用户流量的使用.但是对图片和视频不进行压缩,因为图片和视频的压缩率很小,而且处理所需要的服务器资源很大. 2.实现原理: ...

  8. oracle使用dbms_metadata包取得所有对象DDL语句

    当我们想要查看某个表或者是表空间的DDL的时候,可以利用dbms_metadata.get_ddl这个包来查看. dbms_metadata包中的get_ddl函数详细参数 GET_DDL函数返回创建 ...

  9. Mishka and Interesting sum Codeforces Round #365 (树状数组)

    树状数组,与Turing Tree类似. xr[i]表示从1到i的抑或,树状数组维护从1到i每个数只考虑一次的异或,结果为sum(r) ^ sum(l) ^ xr[r] ^ xr[l] 其中xr[r] ...

  10. bootstrap组件 2

    bootstrap组件2 <!DOCTYPE html> <html lang="zh-cn"> <head > <meta charse ...