C#如何读取excel????
一个excel有多个sheet,如何去动态的读取所有的sheet,下面的这个读取excel的方法,传递的sheet是写死的,直接把sheet名传过去了,如何根据文件获取到所有的sheet名,或者直接默认读取第一个sheet也行。
public void LoadData(string FileSource, string StyleSheet)
{
string strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = " + @FileSource + ";Extended Properties=Excel 8.0 ";
OleDbConnection myConn = new OleDbConnection(strCon);
myConn.Open(); //打开数据链接,得到一个数据集
DataSet myDataSet = new DataSet(); //得到自己的DataSet对象
string StrSql = "select * from [ " + StyleSheet + "$] ";
OleDbDataAdapter myCommand = new OleDbDataAdapter(StrSql, myConn); //创建一个 DataSet对象
myCommand.Fill(myDataSet, "[ " + StyleSheet + "$] ");
myCommand.Dispose();
DataTable DT = myDataSet.Tables[ "[ " + StyleSheet + "$] "];
myConn.Close();
myCommand.Dispose();
}
------解决方案--------------------利用Excel组件
object objOpt = System.Reflection.Missing.Value;
ApplicationClass appTemp = new ApplicationClass();
Workbooks wbsTemp = appTemp.Workbooks;
wbsTemp.Open(FileExcelPath, objOpt, false, objOpt, objOpt, objOpt, true, objOpt, objOpt, true, objOpt, objOpt, objOpt, objOpt, objOpt );
_Workbook wbTemp = wbsTemp.get_Item(1);
Sheets sheetsTemp = wbTemp.Worksheets;
for(int i = 0; i < sheetsTemp.Count; i++ )
{
_Worksheet sheetTemp = (_Worksheet )sheetsTemp.get_Item(i + 1 );
//sheetTemp.Name为表单名称
}
wbTemp.Save();
appTemp.Quit();