asp.net Import and export for Excel files is one of the most common features. The example in this article describes how ASP.net uses Npoi to import export Excel. Share for everyone to use for reference. The specific methods are as follows:
When you export Excel using Npoi, the server can not install any Office components, typically exported with Npoi export Excel file, the guide Excel also conforms to the specification, open without any file damage and so on. However, when you make an import or use OLE DB, the import on the server side seems to require Office components to be installed.
First, Npoi export/download Excel
The specific function code is as follows:
public void Npoiexcel (DataTable dt, string title) {Npoi. HSSF. Usermodel.hssfworkbook book = new Npoi. 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 (int i = 0; i < dt. Columns.count; i++) {Icell cell = HeaderRow.
Createcell (i); Cell.
CellStyle = style; Cell. Setcellvalue (dt. Columns[i].
ColumnName);
} MemoryStream ms = new MemoryStream (); 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 (); }
Second, ASP.net import Excel
The import is still in OLE DB this way, interested friends can try other methods.
The specific function code is as follows:
<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
static System.Data.DataSet excelsqlconnection (string filepath, string TableName)
{
string strcon = "Provider=Microsoft.Jet.OLEDB.4.0;Data source= + filepath +"; Extended properties= ' Excel 8.0; Hdr=yes;imex=1 ' ";
OleDbConnection excelconn = new OleDbConnection (Strcon);
Try
{
string strcom = string. Format ("select * from [sheet1$]");
Excelconn.open ();
OleDbDataAdapter mycommand = new OleDbDataAdapter (strcom, excelconn);
DataSet ds = new DataSet ();
Mycommand.fill (ds, "[" + tablename + "$]");
Excelconn.close ();
return ds;
}
Catch
{
excelconn.close ();
return null;
}
}
It is believed that this article has certain reference value to the ASP.net program design of everybody.