public MemoryStream GridToExcelByNPOI(DataTable dt, string strExcelFileName)
{
HSSFWorkbook wk = new HSSFWorkbook();
ISheet tb = wk.CreateSheet("mySheet");
for (int i = 0; i < dt.Rows.Count; i++)
{
if (i == 0)
{
IRow row = tb.CreateRow(i);
for (int j = 0; j < dt.Columns.Count; j++)
{
ICell cell = row.CreateCell(j);
HSSFCellStyle style = (HSSFCellStyle)wk.CreateCellStyle();
HSSFFont font=(HSSFFont)wk.CreateFont();
font.FontHeightInPoints=12;
style.SetFont(font);
cell.CellStyle = style;
cell.SetCellValue(dt.Rows[i][j].ToString());
}
}
else
{
IRow row = tb.CreateRow(i);
for (int j = 0; j < dt.Columns.Count; j++)
{
ICell cell = row.CreateCell(j);
cell.SetCellValue(dt.Rows[i][j].ToString());
}
}
}
for (int k = 0; k < dt.Columns.Count; k++)
{
string str = "";
for (int f = 0; f < dt.Rows.Count-1;f++ )
{
string cellstr = dt.Rows[f][k].ToString();
if (cellstr.Length < dt.Rows[f+1][k].ToString().Length)
{
cellstr = dt.Rows[f + 1][k].ToString();
}
str = cellstr;
}
if (str.Length <= 4)
{
tb.SetColumnWidth(k, 15 * 256);
}
else
{
tb.SetColumnWidth(k, 28 * 256);
}
}
System.IO.MemoryStream ms = new System.IO.MemoryStream();
wk.Write(ms);
return ms;
}