Import
Code
/** Filepath: Excel path sheetname: the worksheet at the bottom of Excel is sheet1 by default. Each worksheet is treated as a table */
Public void exceldatasource (string filepath, string sheetname)
{
// HDR = yes. The first row is used as the column name. Excel is similar to a database.
String strconn = "provider = Microsoft. Jet. oledb.4.0; Data Source =" + filepath + "; extended properties = 'excel 8.0; HDR = no; IMEX = 1 ;'";
Oledbconnection conn = new oledbconnection (strconn );
Conn. open ();
Int COUNT = 1;
Oledbcommand OMD = conn. createcommand ();
OMD. commandtext = "select * from [" + sheetname + "$]";
OMD. commandtype = commandtype. text;
// This ODR can be operated or filled.
Oledbdatareader ODR = OMD. executereader ();
/** Code below **/
}
Export
Code
/** Filename: name of the Excel file to be exported (custom) ds: exported content **/
Public static void exportdstoxls (page, string filename, dataset DS)
{
Page. response. Clear ();
Page. response. Buffer = true;
Page. response. charset = "UTF-8 ";
Page. response. appendheader ("content-disposition", "attachment; filename =" + filename + system. datetime. now. tostring ("_ yymmdd_hhmm") + ". xls ");
Page. response. contentencoding = system. Text. encoding. getencoding ("UTF-8"); // set the output stream to simplified Chinese
Page. response. contenttype = "application/MS-excel"; // set the output file type to excel.
Page. enableviewstate = false;
Page. response. Write (exporttable (DS ));
Page. response. End ();
}
/** Excel export can be processed as HTML **/
Public static string exporttable (Dataset DS)
{
Stringbuilder DATA = new stringbuilder ();
// Data = Ds. datasetname + "\ n ";
// Prevent Chinese garbled characters
Data. append ("<HTML> Foreach (datatable TB in DS. Tables)
{
Data. append ("<Table cellpadding = '1' style = 'border-collapse: collapse; '> ");
// Write the column name
Data. append ("<tr> ");
Foreach (datacolumn column in TB. columns)
{
Data. append ("<TD style = 'border: solid 1px black; text-align: Center'> <B>" + column. columnname + "</B> </TD> ");
}
Data. append ("</tr> ");
// Write data
Foreach (datarow row in TB. Rows)
{
Data. append ("<tr> ");
Foreach (datacolumn column in TB. columns)
{
// List all column values. The following code depends on your needs.
If (column. columnname = "no .")
Data. append ("<TD style = 'border: solid 1px # cccccc; text-align: Center'>" + row [column]. tostring () + "# </TD> ");
Else
Data. append ("<TD style = 'border: solid 1px # cccccc; text-align: Center'>" + row [column]. tostring () + "</TD> ");
}
Data. append ("</tr> ");
}
Data. append ("</table> ");
}
Data. append ("</body>
Return data. tostring ();
}