乔山办公网我们一直在努力
您的位置:乔山办公网 > excel表格制作 > C#WPF应用程序怎样读取excel表格数据?-wpf导入excel,wpf excel

C#WPF应用程序怎样读取excel表格数据?-wpf导入excel,wpf excel

作者:乔山办公网日期:

返回目录:excel表格制作


有一个对WPF的开源DLL,叫做NPOI开发包,里面集成了几乎所有EXCEL的功能。可以去阅读一下相关文档。如果需要,可以自行百度查找NPOI开发包。
一般做项目的时候都是用这个做的。

System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Open)这个方法打开文件的时候是以只读共享的方式打开的,但若此文件已被一个拥有写权限的进程打开的话,就无法读取了,因此需要使用System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Open,System.IO.FileAccess.Read,FileShare.ReadWrite);设置文件共享方式为读写,FileShare.ReadWrite,这样的话,就可以打开了
public static DataTable ExcelToDataTable(string strExcelFileName, string strSheetName)
        {
            //源的定义
            string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + strExcelFileName + ";" + "Extended Properties='Excel 8.0;HDR=NO;IMEX=1';";
            
            //Sql语句
            //string strExcel = string.Format("select * from [{0}$]", strSheetName); 这是一种方法
            string strExcel = "select * from  [" + strSheetName+"]";//[sheet1$]

            //定义存放的数据表
            DataSet ds = new DataSet();

            //连接数据源
            OleDbConnection conn = new OleDbConnection(strConn);

            conn.Open();

            //适配到数据源
            OleDbDataAdapter adapter = new OleDbDataAdapter(strExcel, strConn);
            adapter.Fill(ds, strSheetName);

            conn.Close();

            return ds.Tables[strSheetName];
        }


读取excel的代码636f7079e799bee5baa6e997aee7ad94362,http://codeo.cn



使用OLEDB

大致结构为:
using(var con = new OleDbConnection("连接字符串"))
{
con.Open();
var cmd = con.CreateCommand();
cmd.CommandText = " SELECT STATEMENT ";
using(var reader = cmd.ExecuteReader())
{
while(reader.Read())

{
//从reader中获取对应列值放到数组中
}
}

}

相关阅读

关键词不能为空
极力推荐

ppt怎么做_excel表格制作_office365_word文档_365办公网