protected override void Export_Click(object sender, EventArgs e)
{
if (templeId == 0)
if (!string.IsNullOrEmpty(Request.QueryString["TempleID"]))
int.TryParse(Request.QueryString["TempleID"], out templeId);
if (templeId == 0)
{
AlertLabel.Text = MessagePage.GetDivCueMsg(MsgCueDiv.UnSuccess, "No data.");
return;
}
var templeInfo = new EMS_ContainerTemplate().GetModel(templeId);
var dt = new EMS_ContainerDetailTemplate().GetListById(templeId);
List<int> ColumnsWidth = new List<int>() { 14, templeInfo.ContainerTemplateName.Length, 0, 0 };
IWorkbook workbook = new HSSFWorkbook();
ISheet sheet = workbook.CreateSheet("sheet");
IRow row0 = sheet.CreateRow(0);
row0.CreateCell(0).SetCellValue("Template Name:");
row0.CreateCell(1).SetCellValue(templeInfo.ContainerTemplateName);
Dictionary<string, string> dicColumns = new Dictionary<string, string>();
dicColumns.Add("ItemCode", "Item ID");
dicColumns.Add("ItemName", "Item Name");
dicColumns.Add("DefaultUnit", "Basic Unit");
dicColumns.Add("Qty", "Planned Qty");
IRow row2 = sheet.CreateRow(1);
int index = 0;
Action<string> act = b =>
{
if (!string.IsNullOrEmpty(b))
{
if (index < ColumnsWidth.Count)
{
if (b.Length > ColumnsWidth[index])
{
ColumnsWidth[index] = b.Length;
}
}
else
{
ColumnsWidth.Add(b.Length);
}
}
};
foreach (var item in dicColumns)
{
act(item.Value);
row2.CreateCell(index).SetCellValue(item.Value);
index++;
}
sheet.CreateRow(2);
for (int i = 3; i < dt.Rows.Count + 3; i++)
{
IRow row = sheet.CreateRow(i);
index = 0;
foreach (var item in dicColumns)
{
string cellString = DataConvert.ToString(dt.Rows[i - 3][item.Key]);
act(cellString);
row.CreateCell(index).SetCellValue(cellString);
index++;
}
}
//set columns width
for (int i = 0; i < ColumnsWidth.Count; i++)
{
sheet.SetColumnWidth(i, ColumnsWidth[i] * 256);
}
//write to steam
MemoryStream stream = new MemoryStream();
workbook.Write(stream);
var buf = stream.ToArray();
//epport
HttpContext.Current.Response.ContentType = "application/octet-stream";
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode($"PackingTemplate_{ReplaceFile(templeInfo.ContainerTemplateName)}.xls", System.Text.Encoding.UTF8));
HttpContext.Current.Response.BinaryWrite(buf);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
}
C# NPOI 操作
于 2024-09-03 17:44:04 首次发布