problem: use C # programs to read Excel files, including the suffix. xls and. xlsx
Believe that many friends have in the program to read Excel file requirements, I in the process of research also read a lot of articles, the basic ideas are correct, but some code is not verified, in the actual operation of the process will encounter some problems, after groping, finally summed up a set of feasible solutions, Here to share with you.
There are several ways to read Excel, and I've chosen a more efficient way to store the data that is being read into a dataset.
The code is as follows:
Using system;using system.collections.generic;using system.linq;using system.text;using System.Threading.Tasks; Using system.data.oledb;using system.data;namespace convertexcel2dll{//implements the ability to read Excel files class Readexcel {p Rivate static String StrCon1 = "Provider=Microsoft.Jet.OLEDB.4.0;Data source="; private static String StrCon2 = "; Extended properties= ' Excel 8.0; Hdr=no;imex=1, ' "; public static String M_filepathexcel = "C:\\test.xls"; /* Read data from Excel */public static DataSet Importexceltodataset () {OleDbConnection conn = new Oledbco Nnection (strCon1 + m_filepathexcel + strCon2); try {Conn. Open (); } catch (InvalidOperationException IE) {console.write ("The connection is opened repeatedly. \ n "); } catch (OleDbException oe) {Console.Write ("A connection level error occurred while opening the connection. \ n "); } OleDbDataAdapter mycommand = new OledbdataadaptER ("select *from [sheet1$]", conn); DataSet myDataSet = new DataSet (); try {Mycommand.fill (myDataSet); Console.WriteLine ("Read OK"); } catch (Exception ex) {Console.Write ("Formation error"); } return myDataSet; } }}
Note: In fact, there is only one point to emphasize, that is StrCon1 StrCon2 and m_filepathexcel format, to note that the space in this area can not be less, single quotation marks can not be less, m_filepathexcel in the \ to escape to the \ \。
The meaning of HDR = yes is the first behavior table header in an Excel table, which does not need to be read out and, if necessary, no. Other meanings can be found on the Internet.
[Windows Issue-4] C # reading Excel files