. NET excel export method,. net excel Export
// Export
Private string outFileName = "";
Private string fullFilename = "";
Private Workbook book = null;
Private Worksheet sheet = null;
Private void AddHeader (string [] dt)
{
Cell cell = null;
Int col = 0;
Foreach (string item in dt)
{
Cell = sheet. Cells [0, col];
Cell. PutValue (item );
Col ++;
}
}
Private void AddBody (DataTable dt, params int [] cl)
{
Int cls = 0;
Foreach (int item in cl)
{
For (int r = 0; r <dt. Rows. Count; r ++)
{
Sheet. Cells [r + 1, cls]. PutValue (dt. Rows [r] [item]. ToString ());
}
Cls ++;
}
}
Public string Export (DataTable dt)
{
Try
{
FullFilename = "Excel ";
Book = new Workbook ();
// Book. Open (tempfilename );
Sheet = book. Worksheets [0];
Sheet. Name = "data ";
// Sheet. Name = sheetName;
// AddTitle (title, dt. Columns. Count );
AddHeader (new string [] {"column 1", "column 2 ",...});
AddBody (dt, number of columns );
Sheet. AutoFitColumns ();
// Sheet. AutoFitRows ();
FileName = System. DateTime. Now. ToString ("yyyymmddhhmmss") + ". xls ";
String SaveFilePath = @ "\ DownLoadFile \" + fileName;
Book. Save (System. AppDomain. CurrentDomain. BaseDirectory + SaveFilePath );
This. fullFilename = System. AppDomain. CurrentDomain. BaseDirectory + SaveFilePath;
// Byte [] array = File. ReadAllBytes (fullFilename );
FileStream fs = new FileStream (fullFilename, FileMode. Open );
Byte [] data = new byte [fs. Length];
Fs. Read (data, 0, data. Length );
BinaryWriter w = new BinaryWriter (fs );
MemoryStream MS = new MemoryStream (data );
W. Write (ms. ToArray ());
W. Close ();
W. Dispose ();
Fs. Close ();
Fs. Dispose ();
// HttpContext. Current. Response. AppendHeader ("Content-Disposition", "attachment; filename =" + fileName );
// HttpContext. Current. Response. BinaryWrite (ms. ToArray ());
// HttpContext. Current. Response. End ();
Ms. Close ();
Ms. Dispose ();
Return fullFilename;
}
Catch (Exception e)
{
Return string. Empty;
}
}
Only the Export (DataTable dt) method is required for calling.