Introduction
Using Npoi to export Excel server can not install any Office components, yesterday in an export using Npoi export Excel, and the guide Excel also conforms to the specification, open without any file corruption and other prompts. However, when you do import or use OLE DB, this way of import on the server side seems to need to install Office components, there is no need to install components and can be imported as usual?
Npoi Export/Download Excel
Public voidNpoiexcel (DataTable DT,stringtitle) {Npoi. HSSF. Usermodel.hssfworkbook Book=NewNpoi. HSSF. Usermodel.hssfworkbook (); Npoi. Ss. Usermodel.isheet sheet= Book. Createsheet ("Sheet1"); Npoi. Ss. Usermodel.irow HeaderRow= Sheet. CreateRow (0); Icellstyle style=Book . Createcellstyle (); Style. Alignment=HorizontalAlignment.Center; Style. VerticalAlignment=Verticalalignment.center; for(inti =0; i < dt. Columns.count; i++) {Icell cell=HeaderRow. Createcell (i); Cell. CellStyle=style; Cell. Setcellvalue (dt. Columns[i]. ColumnName); } MemoryStream Ms=NewMemoryStream (); Book. Write (MS); Response.AddHeader ("content-disposition",string. Format ("attachment; Filename={0}.xls", Httputility.urlencode (title +"_"+ DateTime.Now.ToString ("YYYY-MM-DD") , System.Text.Encoding.UTF8)); Response.BinaryWrite (Ms. ToArray ()); Response.End (); Book=NULL; Ms. Close (); Ms. Dispose (); }
View Code
ASP. NET Import
Import is still in OLE DB this way, is there any other way to get it done?
/// <summary> ///connect Excel to read Excel data and return DataSet data collection/// </summary> /// <param name= "filepath" >Excel Server Path</param> /// <param name= "TableName" >Excel table name</param> /// <returns></returns> Public StaticSystem.Data.DataSet Excelsqlconnection (stringFilePathstringtableName) { stringStrcon ="Provider=Microsoft.Jet.OLEDB.4.0;Data source="+ filepath +"; Extended properties= ' Excel 8.0; Hdr=yes;imex=1 '"; OleDbConnection Excelconn=NewOleDbConnection (Strcon); Try { stringstrcom =string. Format ("SELECT * FROM [sheet1$]"); Excelconn.open (); OleDbDataAdapter mycommand=NewOleDbDataAdapter (strcom, excelconn); DataSet DS=NewDataSet (); Mycommand.fill (DS,"["+ TableName +"$]"); Excelconn.close (); returnds; } Catch{excelconn.close (); return NULL; } }
View Code
ASP. NET exports Excel using Npoi