C # EXCEL import and export,
1: EXCEL export is very simple. Upload the EXCEL template to the project, save the browsing URL (excelUrl), and then:
Window. location. href = "http: // localhost: 10086/yuanxin/Resources/BusRoute.xlsx" // EXCEL browsing path
You can also use <a href = "excelUrl"> </a>.
2. Import and obtain data in EXCEL. paste the following code directly:
Public class ExcelHelp {// obtain the http Request object public static HttpRequest baseRequest = HttpContext. current. request; // obtain the http Request Response object public static HttpResponse baseResponse = HttpContext. current. response; /// <summary> /// obtain the EXCEL file data of the Post request /// </summary> /// <param name = "fileFormName"> EXCEL form name </param >/// <returns> </returns> public static DataTable GetExcelData (string fileFormName) {// get Post please -- Form file name string uploadFileName = baseRequest. files [fileFormName]. fileName; // upload the file to the specified directory (Project root directory/Resources/uploadFileName) -- you can adjust string path = HttpContext according to the project file directory. current. server. mapPath ("~ /Resources/"+ uploadFileName); baseRequest. files [fileFormName]. saveAs (path); DataTable dataTable = new DataTable (); DataSet dataSet = new DataSet (); // parse file data and save it to the server. // note: "HDR = yes; "The first line of an Excel file is a column name rather than data." HDR = No; "is the opposite of the previous one. // "IMEX = 1" if the data types in the column are inconsistent, use "IMEX = 1" to avoid data type conflicts. String strConn = string. format ("Provider = Microsoft. ACE. OLEDB.12.0; Data Source = {0}; Extended Properties = 'excel 8.0; HDR = Yes; IMEX = 1'; ", path ); oleDbDataAdapter oada = new OleDbDataAdapter ("select * from [Sheet1 $]", strConn); oada. fill (dataSet); if (dataSet. tables. count> 0) {dataTable = dataSet. tables [0];} if (System. IO. file. exists (path) {// delete System if it Exists. IO. file. delete (path) ;}return dataTable ;}}
Note: use C # To create an EXCEL file, which has not been studied yet. You can add it later.
When I was writing this blog, I checked the following help blog: Import excel error: External table is not the expected format Solution