C#后台为EXCEL添加下拉列表(有效性)

string path = “Teme\D\Di.xlsx”;
XSSFWorkbook xssfworkbook;
try
{
using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.ReadWrite))
{
xssfworkbook = new XSSFWorkbook(fs);
fs.Close();
}
}
catch(Exception ee)
{
WriteMessageToCardClient(MsgState.Err, “下载失败,未找到模板文件!”); return;
}
XSSFSheet sheet1 = xssfworkbook.GetSheet(“Sheet1”) as XSSFSheet;
XSSFSheet bizSheet = xssfworkbook.CreateSheet(“bizSheet”) as XSSFSheet;
XSSFDataValidationHelper dvHelper = new XSSFDataValidationHelper(sheet1);
for (int i = 0; i < 10000; i++) //Biz表里创建足够多的行
{
bizSheet.CreateRow(i);
}
//将##存到excel中
range.RefersToFormula = string.Format("{0}!$B 1 : 1: 1:B${1}", “bizSheet”, Name.Keys.Count);
range.NameName = “ColB”;
dvConstraint = (XSSFDataValidationConstraint)dvHelper.CreateFormulaListConstraint(range.NameName);
CellRangeAddressList addressList2 = null;
XSSFDataValidation validation2 = null;
addressList2 = new CellRangeAddressList(1, 65535, 1, 1);
validation2 = (XSSFDataValidation)dvHelper.CreateValidation(dvConstraint, addressList2);
validation2.CreateErrorBox(“数据不合法”, “请选择下拉列表中的值”);
validation2.ShowErrorBox = true;
sheet1.AddValidationData(validation2);

        if (xssfworkbook != null)
        {
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Buffer = true;
            HttpContext.Current.Response.Charset = "utf-8";
            HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode("模板.xlsx"));
            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
            HttpContext.Current.Response.ContentType = "application/ms-excel";
            xssfworkbook.Write(HttpContext.Current.Response.OutputStream);
            HttpContext.Current.Response.End();
        }

你可能感兴趣的:(C#后台为EXCEL添加下拉列表(有效性))