If you create a new project, you must first add Microsoft. office. core and Microsoft. office. interop. the Exce applications can then be easily operated. The sample code (only simple read/write is implemented ):
private Excel._Application excelApp;private Workbook wbclass;excelApp = new Excel.Application();object objOpt = System.Reflection.Missing.Value; wbclass = (Workbook)excelApp.Workbooks.Open("E:\Book6.xlsx", objOpt, false, objOpt, objOpt, objOpt, true, objOpt, objOpt, true, objOpt, objOpt, objOpt, objOpt, objOpt);
The above declaration, reference, and pass the path of the excel file to him
Obtain the names of all tables:
List List = new List ();
Excel. Sheets sheets = wbclass. Worksheets;
String sheetNams = string. Empty;
Foreach (Excel. Worksheet sheet in sheets)
{
List. Add (sheet. Name );
}
Get the data in a table. Here we get the data in the sheet table:
Public Excel. worksheet GetWorksheetByName (string name) {Excel. worksheet sheet = null; Excel. sheets sheets = wbclass. worksheets; foreach (Excel. worksheet s in sheets) {if (s. name = name) {sheet = s; break;} return sheet;} public System. data. dataTable GetDateTable (string name) {System. data. dataTable dt = new System. data. dataTable (); var worksheet = GetWorksheetByName (name); // call the preceding method and obtain String cellContent; int iRowCount = worksheet. usedRange. rows. count; int iColCount = worksheet. usedRange. columns. count; Excel. range range; for (int iRow = 1; iRow <= iRowCount; iRow ++) {DataRow dr = dt. newRow (); for (int iCol = 1; iCol <= iColCount; iCol ++) {range = (Excel. range) worksheet. cells [iRow, iCol]; cellContent = (range. value2 = null )? "": Range. text. toString (); if (iRow = 1) {dt. columns. add (cellContent) ;}else {dr [iCol-1] = cellContent ;}} if (iRow! = 1) dt. Rows. Add (dr);} return dt ;}
What we get above is
System.Data.DataTable
For details about how to extract data, see the following:
Var dataTable = GetDateTable ("Sheet1"); // call the preceding method foreach (DataRow row in dataTable. rows) {string a = (string) row [2]; string B = (string) row [4];
}