最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
C#使用NPOI跨域生成excel文件并且下载例子
时间:2016-03-05 编辑:简简单单 来源:一聚教程网
1、服务端,根据参数获取数据数据
引用dll:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using NPOI.HSSF.UserModel;
using NPOI.HPSF;
using NPOI.POIFS.FileSystem;
using NPOI.SS.UserModel;
using NPOI.SS.Formula.Functions;
using System.IO;
初始化NPOI的实体:
HSSFWorkbook hssfworkbook;
void InitializeWorkbook()
{
hssfworkbook = new HSSFWorkbook();
////create a entry of DocumentSummaryInformation
DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
dsi.Company = "AP分析";
hssfworkbook.DocumentSummaryInformation = dsi;
////create a entry of SummaryInformation
SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
si.Subject = "导出分析结果";
hssfworkbook.SummaryInformation = si;
}
设置表头和数据对应:
private string Pengzhuang(int taskid, int tasktype)
{
string url = "";
AP.BLL.CrashResult crashbll = new AP.BLL.CrashResult();
List
int count = 0;
//用npoi先写表头
InitializeWorkbook();
ISheet sheet1 = hssfworkbook.CreateSheet("任务" + taskid + "导出结果");
IRow row1 = sheet1.CreateRow(0);
row1.CreateCell(0).SetCellValue("序号");
row1.CreateCell(1).SetCellValue("Mac");
row1.CreateCell(2).SetCellValue("碰撞率");
int x = 1;
foreach (AP.Model.CrashResult cs in list)
{
IRow row = sheet1.CreateRow(x);
row.CreateCell(0).SetCellValue(cs.ID);
row.CreateCell(1).SetCellValue(cs.Mac);
row.CreateCell(2).SetCellValue(cs.CrashCount.ToString());
x++;
}
url = WriteToFile();
return url;
}
返回文件下载的url:
[WebMethod]
public void Exceldown(int taskid,int tasktype)
{
string url = "";
switch(tasktype)
{
case 2://
url = Pengzhuang(taskid,tasktype);
break;
default:
url = "#";
break;
}
CheckResponse.SendResponse(url);
}
文件生成:
string WriteToFile()
{
//Write the stream data of workbook to the root directory
string serverImagePath = "cardxls";
string filename = hssfworkbook.GetSheetAt(0).SheetName + ".xls";
string temppath = System.Web.HttpContext.Current.Server.MapPath(serverImagePath);
if (!Directory.Exists(temppath))
{
Directory.CreateDirectory(temppath);
}
FileStream file = new FileStream(System.Web.HttpContext.Current.Server.MapPath(serverImagePath + "/" + filename), FileMode.Create);
hssfworkbook.Write(file);
file.Close();
return "/" + serverImagePath + "/" + filename;
}
2、js ajax调用服务
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="FileDown.aspx.cs" Inherits="Ap.Service.FileDown" %>
相关文章
- C#复制数组的两种方式及效率比较解读 10-24
- ASP.NET Identity用法解析 10-24
- ASP.NET MVC使用Identity增删改查用户介绍 10-24
- C语言中atoi函数模拟实现介绍 10-18
- .Net反向代理组件Yarp用法介绍 10-10
- .NET使用YARP通过编码方式配置域名转发实现反向代理教程 10-10