本来代码已经写好了,传递给前台文件路径就可以,后来同事告诉我,给路径可能下载不了,文件可能放在另一台服务器,告诉我说用流进行下载,然后就开始百度加上找现在公司的代码,做出来了,感觉怪怪的。
//判断路径是否存在,不存在则创建
var basePath = Path.Combine(ProjectConfig.BaseFolder));
if(!File.Exists(basePath )){System.IO.Directory.CreateDirectory(basePath);}
//待读取文件路径
string filePath = Path.Combine(basePath,"xxx.xls");
//获取HSSFWorkbook对象
HSSFWorkbook workbook = (HSSFWorkbook)OpenWorkbook(filePath);
//操作sheet
ISheet sheet = workbook.GetSheetAt(0);
//设置生成下拉框的行和列;绑定下拉框和作用区域
sheet.AddValidationData(new HSSFDataValidation(new CellRangeAddressList(4, 30, 0, 0),
DVConstraint.CreateExplicitListConstraint(字符串类型数组)));
//设置标题
ICell titleRow = sheet.GetRow(0).GetCell(0);
titleRow.SetCellValue(titleRow.StringCellValue.Replace("x", year));
//导出Excel
FileStream stream = new FileStream(filePath, FileMode.Create, System.IO.FileAccess.ReadWrite);
workbook.Write(stream);//设置模板写入流中用于导出
//流转换成二进制数组
BinaryReader r = new BinaryReader(stream);
r.BaseStream.Seek(0, SeekOrigin.Begin);//将文件指针设置到文件开
byte[] pReadByte = r.ReadBytes((int)r.BaseStream.Length);
//关闭流
stream.Close();
stream.Dispose();
//返回待下载文件
Stream stream = new MemoryStream(buffer);
stream.Seek(0, SeekOrigin.Begin);//设置stream的position为流的开始
return stream;
//Controller代码
public HttpResponseMessage xxx()
{
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
var res = _aviationProtectionService.xxx();//返回的流
result.Content = new StreamContent(res);
result.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
result.Content.Headers.ContentDisposition.FileName = "xxx.xls";
return result;
}