DataTable ExcelTable;
DataSet ds = new DataSet();
//Excel的连接
OleDbConnection objConn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + sExcelFile + ";" + "Extended Properties=Excel 8.0;");
objConn.Open();
DataTable schemaTable = objConn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null);
string tableName = schemaTable.Rows[0][2].ToString().Trim();//获取 Excel 的表名,默认值是sheet1
string strSql = "select * from [" + tableName + "]";
OleDbCommand objCmd = new OleDbCommand(strSql, objConn);
OleDbDataAdapter myData = new OleDbDataAdapter(strSql, objConn);
myData.Fill(ds, tableName);//填充数据
dgBom.DataSource =ds;
dgBom.DataBind();
objConn.Close();
ExcelTable = ds.Tables[tableName];
int iColums = ExcelTable.Columns.Count;//列数
int iRows = ExcelTable.Rows.Count;//行数
第3行第3列数据
strData=ExcelTable.Rows[3][3].ToString();
这样获取是可以。但是我的excel文件是不规则的。前两行数据没有用。我只要第3行第3列的值。是直接从excel中获取这个值。这个应该怎么弄???
是直接操作excel的吗?可以试试NPOI,现在操作excel,这个使用还是很频繁的
是直接操作excel。
@詺*篂: 对啊,NPOI就是可以直接操作excel
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
.....
using (FileStream fileStream = new FileStream(excelPath, FileMode.Open, FileAccess.Read))
{
HSSFWorkbook workbook = new HSSFWorkbook(fileStream);
HSSFFormulaEvaluator evaluator = new HSSFFormulaEvaluator(workbook);
HSSFSheet sheet = workbook.GetSheetAt(0) as HSSFSheet;
HSSFRow firstRow = sheet.GetRow(2) as HSSFRow;
//判断此行是否有值
if (firstRow.GetCell(2) != null)
{
.............//根据此行类型获取值.
}
}