@Override
public void mediadown(HttpServletResponse response,ArrayList<media> med,HttpSession session) throws IOException {
// 1.创建一个workbook,对应一个Excel文件
HSSFWorkbook wb = new HSSFWorkbook();
// 2.在workbook中添加一个sheet,对应Excel中的一个sheet
HSSFSheet sheet = wb.createSheet("媒体信息表");
// 3.在sheet中添加表头第0行,老版本poi对excel行数列数有限制short
HSSFRow row = sheet.createRow((int) 0);
// 4.创建单元格,设置值表头,设置表头居中
HSSFCellStyle style = wb.createCellStyle();
// 居中格式
HSSFCell cell = row.createCell(0);
cell.setCellValue("id");
cell.setCellStyle(style);
cell = row.createCell(1);
cell.setCellValue("账户id");
cell.setCellStyle(style);
cell = row.createCell(2);
cell.setCellValue("媒体名称");
cell.setCellStyle(style);
cell = row.createCell(3);
cell.setCellValue("广告位id");
cell.setCellStyle(style);
cell = row.createCell(4);
cell.setCellValue("广告位名称");
cell.setCellStyle(style);
cell = row.createCell(5);
cell.setCellValue("操作系统");
cell.setCellStyle(style);
cell = row.createCell(6);
cell.setCellValue("广告位样式");
cell.setCellStyle(style);
cell = row.createCell(7);
cell.setCellValue("尺寸");
cell.setCellStyle(style);
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
int i=0;
for(media hour:med){
row = sheet.createRow(i + 1);
row.createCell(0).setCellValue(hour.getId());
row.createCell(1).setCellValue(hour.getAccountid());
row.createCell(2).setCellValue(hour.getMedia());
row.createCell(3).setCellValue(hour.getApid());
row.createCell(4).setCellValue(hour.getAdname());
row.createCell(5).setCellValue(hour.getOs());
row.createCell(6).setCellValue(hour.getApstyle());
row.createCell(7).setCellValue(hour.getApsizie());
i++;
}
FileOutputStream out =new FileOutputStream("E:/test/媒体信息表.xls");
wb.write(out);
out.close();
这里的问题时可以下载 不报错但是名字不会变化,点击下载一次 第2次点击就不好使了不会自动命名 +1等 求解决,最好能探出下载框还不冲突,无语死了
}
最后会报这个错误getOutputStream() has already been called for this response
网上的方案我都是了不好使 我这里是后台,前台就一个下载2个字 ,后台里面 这些 方法都没有,网上说的方法 ,求大神帮忙
<%@page contentType="text/html;charset=UTF-8"%>
<%@page language="java" pageEncoding="UTF-8"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%
response.setContentType("text/html;charset=UTF-8");
%>
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
<small>媒体管理</small>
</h1>
<ol class="breadcrumb">
<li><a href="remove.do"><i class="fa fa-dashboard"></i> 注销</a></li>
</ol>
</section>
<!-- Main content -->
<section class="content">
<div class="row">
<div class="col-xs-12">
<div class="box">
<div class="box-header">
<div class="box-tools">
<div class="input-group input-group-sm" style="width: 150px;"></div>
</div>
</div>
<!-- /.box-header -->
<div class="box-body table-responsive no-padding">
<table class="table table-hover">
<tr>
<th>ID</th>
<th>账户ID</th>
<th>媒体名称</th>
<th>广告位ID</th>
<th>广告位名称</th>
<th>操作系统</th>
<th>广告位样式</th>
<th>尺寸</th>
<th>操作</th>
</tr>
<c:forEach var="med" items="${med }">
<tr>
<td>${med.id}</td>
<td>${med.accountid }</td>
<td>${med.media }</td>
<td>${med.apid }</td>
<td>${med.adname }</td>
<td>${med.os }</td>
<td>${med.apstyle }</td>
<td>${med.apsizie }</td>
<td><a href="deletemed.do?id=${med.id}">删除</a>
</td>
</tr>
</c:forEach>
</table>
</div>
</div>
<a href="addmed.do"
style="font-size: 16px;position: relative;left:420px;"><input
style="height: 28px;" type="button" value="新增媒体" />
</a>
<%
out.clear();
out = pageContext.pushBody();
%>
<a href="media.do?down=1"
style="font-size: 14px; position: relative;left:800px;">下载</a>
<!-- /.box -->
</div>
</div>
</section>
<!-- /.content -->
这个是前段页面我按网上说的加了那几句代码不过 页面都不显示了...求解决
这个jsp页面 是2级页面 被包含外围还有一个页面所以没有body 等 外围用<jsp:include 标签进来的
豆豆 给你吧 我解决了 虽然用的不是你提供的方法,不过你也挺辛苦的 我的方法是把ServletOutputStream out =response.getOutputStream();这句话放到了response.reset();上面,就不会出现那个异常了 不过 别的下载又抛出了新的 异常擦醉死 给你豆 辛苦费把 如果可以加qq常聊
843636292
@skateweb: 哈哈哈,java 和C# 还是有点不同的
@筱浬: 不同的地方多了 你在坑人啊 擦 好在自己解决了 醉了
@skateweb: 不是我矫情,我加了qq也没用 公司禁用的
@筱浬: 拉倒吧
@skateweb: 不是啊,我一开始问了你是不是导出.我才接着说的 坑你了也实在是不好意思.无心之失.你要豆子我给你啊 我基本上不用豆子的
@筱浬: 没事
是导出对吧?
是的 下载 的时候就有冲突,但是不影响程序 ,不过控制台报错 网上的方法都是了 还是不好时 擦擦擦求解
@skateweb: 现在下班了.忘记给你demo了
@筱浬: 没事 我qq 843636292可以加好友问题解决绝对给豆 不忽悠人 求大神帮忙啊 我这里不熟悉,摸爬滚打了半天了
@筱浬: 我也先下班了 回到家在回复你 ....
@skateweb: 明天给你看看 我做的导出
@筱浬: 好的 谢谢 拉勾啊擦
@skateweb: http://download.local.imcba.cn/NPOI(ImportExport).zip
@筱浬: 我一会到公司了看看
@skateweb:
public class NPOIHelper
{
/// <summary>
/// dataTable转换成Json格式
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static string DataTableToJson(string jsonName, DataTable dt)
{
StringBuilder Json = new StringBuilder();
Json.Append("{\"" + jsonName + "\":[");
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
Json.Append("{");
for (int j = 0; j < dt.Columns.Count; j++)
{
Json.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":\"" + dt.Rows[i][j].ToString() + "\"");
if (j < dt.Columns.Count - 1)
{
Json.Append(",");
}
}
Json.Append("}");
if (i < dt.Rows.Count - 1)
{
Json.Append(",");
}
}
}
Json.Append("]}");
return Json.ToString();
}
public static string UrlConvertorAbsolute(string relativeUrl)
{
string tmpRootDir = System.Web.HttpContext.Current.Server.MapPath(HttpContext.Current.Request.ApplicationPath.ToString());
string absoluteUrl = tmpRootDir + relativeUrl.Replace(@"/", @"\");
if (!Directory.Exists(absoluteUrl))
{
Directory.CreateDirectory(absoluteUrl);
}
return absoluteUrl;
}
public static string GenerateExcelName()
{
int rand;
char code;
string excelName = string.Empty;
Random random = new Random();
for (int i = 0; i < 7; i++)
{
rand = random.Next();
code = (char)('0' + (char)(rand % 10));
excelName += code.ToString();
}
return DateTime.Now.ToString("yyyyMMdd") + excelName;
}
#region 导出Pdf
public static void ExportPdf(string url)
{
//string url = Request.Url.Host;
string pdfpath = string.Empty;
string filanamepath = string.Empty;
string path = string.Empty;
System.Diagnostics.Process proc = null;
string isDown = string.Empty;
try
{
string RequestParam = string.Empty;
string RequestUrl = string.Empty;
if (!String.IsNullOrEmpty(System.Web.HttpContext.Current.Request.QueryString["RequestParam"]))
RequestParam = System.Web.HttpContext.Current.Request.QueryString["RequestParam"];
if (!String.IsNullOrEmpty(System.Web.HttpContext.Current.Request.QueryString["RequestUrl"]))
RequestUrl = System.Web.HttpContext.Current.Request.QueryString["RequestUrl"];
if (!String.IsNullOrEmpty(System.Web.HttpContext.Current.Request.QueryString["isDown"]))
isDown = System.Web.HttpContext.Current.Request.QueryString["isDown"];
string uploadPath = HttpContext.Current.Server.MapPath("~\\PDF\\");
if (!Directory.Exists(uploadPath))
{
Directory.CreateDirectory(uploadPath);
}
proc = new System.Diagnostics.Process();
proc.StartInfo.FileName = System.Web.HttpContext.Current.Server.MapPath("~/AppTools/HtmlToPdf2/") + "wkhtmltopdf.exe";
Log.SaveNote(System.Web.HttpContext.Current.Server.MapPath("~/AppTools/HtmlToPdf2/") + "wkhtmltopdf.exe");
proc.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
path = Guid.NewGuid().ToString();
//path = "testPDF";
RequestUrl = url;
//
var startArguments = String.Format(@"{0} ""{1}"" ""{2}.pdf""", RequestParam, ServerHost + RequestUrl, System.Web.HttpContext.Current.Server.MapPath("/PDF/Questionnaire/") + path);
proc.StartInfo.Arguments = startArguments;
Log.SaveNote("Export PDF: " + startArguments);
proc.Start();
proc.WaitForExit();
proc.Close();
// return;
Log.SaveNote(SessionMgr.Username + " print at " + DateTime.Now.ToString());
string ordertemplateid = System.Web.HttpContext.Current.Request.QueryString["ordertemplateid"] != null ? System.Web.HttpContext.Current.Request.QueryString["ordertemplateid"] : "1";
//HtmlConverter.HtmlTool htmltool = new Business.HtmlConverter.HtmlTool();
if (!Directory.Exists(HttpContext.Current.Server.MapPath("~/PDF/Questionnaire/")))
{
Directory.CreateDirectory(HttpContext.Current.Server.MapPath("~/PDF/Questionnaire/"));
}
pdfpath = "/PDF/Questionnaire/" + path + ".pdf";
filanamepath = System.Web.HttpContext.Current.Server.MapPath(HttpContext.Current.Request.ApplicationPath) + pdfpath;
// htmltool.ToPdf(long.Parse(ordertemplateid), filanamepath);
if (isDown == "1")
{
byte[] BynFile = File.ReadAllBytes(filanamepath);
System.Web.HttpContext.Current.Response.Buffer = true;
System.Web.HttpContext.Current.Response.Clear();
System.Web.HttpContext.Current.Response.Charset = "UTF-8";
System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + path + ".pdf");
System.Web.HttpContext.Current.Response.ContentType = "application/pdf";
System.Web.HttpContext.Current.Response.BinaryWrite(BynFile);
System.Web.HttpContext.Current.Response.Flush();
}
else
{
System.Web.HttpContext.Current.Response.Redirect(pdfpath);
}
}
catch (Exception ex)
{
if (proc != null)
{
proc.Close();
}
Log.SaveException(ex);
}
finally
{
if (proc != null)
{
proc.Close();
}
}
}
/// <summary>
/// 用于生成PDF文件的web服务器(含端口号)
/// </summary>
public static string ServerHost
{
get
{
var host = System.Web.Configuration.WebConfigurationManager.AppSettings["PDFServerHost"];
if (String.IsNullOrWhiteSpace(host))
host = "http://" + System.Web.HttpContext.Current.Request.Url.Authority;// Request.Headers["host"]; //如果没有配置,则使用当前请求页面的地址
return host;
}
}
#endregion
#region NOPI Excel固定列导出
public static Stream RenderDataTableToExcel(DataTable SourceTable, string strHeaderText, string localUrl)
{
MemoryStream ms = new MemoryStream();
NPOI.HSSF.UserModel.HSSFWorkbook workbook = new NPOI.HSSF.UserModel.HSSFWorkbook();
NPOI.SS.UserModel.ISheet sheet = workbook.CreateSheet();
NPOI.SS.UserModel.IRow headerRow = sheet.CreateRow(0);
if (!string.IsNullOrEmpty(strHeaderText)) //当不需要表头的时候下面的 rowIndex 需要从0开始
{
#region 表头及样式
{
headerRow.HeightInPoints = 25;
headerRow.CreateCell(0).SetCellValue(strHeaderText);
HSSFCellStyle headStyle = (HSSFCellStyle)workbook.CreateCellStyle();
// headStyle.Alignment = CellHorizontalAlignment.CENTER;
HSSFFont font = (HSSFFont)workbook.CreateFont();
font.FontHeightInPoints = 20;
font.Boldweight = 700;
headStyle.SetFont(font);
headerRow.GetCell(0).CellStyle = headStyle;
// sheet.AddMergedRegion(new Region(0, 0, 0, dtSource.Columns.Count - 1));
//headerRow.Dispose();
}
#endregion
}
sheet.SetColumnWidth(0, 10 * 400);
sheet.SetColumnWidth(1, 10 * 400);
sheet.SetColumnWidth(2, 15 * 800);
sheet.SetColumnWidth(3, 15 * 400);
headerRow.CreateCell(0).SetCellValue("Firstname");
headerRow.CreateCell(1).SetCellValue("Lastname");
headerRow.CreateCell(2).SetCellValue("Email");
headerRow.CreateCell(3).SetCellValue("Status");
headerRow.CreateCell(3).SetCellValue("is_approved2");
headerRow.CreateCell(3).SetCellValue("IsRegieter");
//headerRow.RowStyle = style;
ICellStyle style = workbook.CreateCellStyle();
//设置单元格的样式:水平对齐居中
//style.Alignment = HorizontalAlignment.CENTER;
//新建一个字体样式对象
IFont font2 = workbook.CreateFont();
//设置字体加粗样式
font2.Boldweight = short.MaxValue;
//使用SetFont方法将字体样式添加到单元格样式中
style.SetFont(font2);
//将新的样式赋给单元格
foreach (var item in headerRow.Cells)
{
item.CellStyle = style;
}
int rowIndex = 1;
foreach (DataRow row in SourceTable.Rows)
{
NPOI.SS.UserModel.IRow dataRow = sheet.CreateRow(rowIndex);
dataRow.CreateCell(0).SetCellValue(row["SocialType"].ToString());
dataRow.CreateCell(1).SetCellValue(row["SocialType"].ToString());
dataRow.CreateCell(2).SetCellValue(row["URL"].ToString());
dataRow.CreateCell(3).SetCellValue(row["CreateTime"].ToString());
rowIndex++;
}
workbook.Write(ms);
ms.Flush();
ms.Position = 0;
sheet = null;
headerRow = null;
workbook = null;
FileStream fs = new FileStream(localUrl, FileMode.Create, FileAccess.Write);
byte[] data = ms.ToArray();
fs.Write(data, 0, data.Length);
fs.Flush();
fs.Close();
data = null;
ms = null;
fs = null;
System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + GenerateExcelName() + ".xls");
System.Web.HttpContext.Current.Response.ContentType = "Application/excel";
System.Web.HttpContext.Current.Response.WriteFile(localUrl);
System.Web.HttpContext.Current.Response.End();
return ms;
}
#endregion
#region NOPI Excel导出全部数据源
/// <summary>
/// DataTable导出到Excel文件
/// </summary>
/// <param name="dtSource">源DataTable</param>
/// <param name="strHeaderText">表头文本</param>
/// <param name="strFileName">保存位置</param>
public static void DataTableToExcel(DataTable dtSource, string strHeaderText, string localUrl)
{
using (MemoryStream ms = DataTableToExcel(dtSource, strHeaderText))
{
if (ms != null)
{
using (FileStream fs = new FileStream(localUrl, FileMode.Create, FileAccess.Write))
{
byte[] data = ms.ToArray();
fs.Write(data, 0, data.Length);
fs.Flush();
fs.Close();
// System.Web.HttpContext.Current.Response.AddHeader("Content-Type", "application/notepad");
System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + GenerateExcelName() + ".xls");
System.Web.HttpContext.Current.Response.ContentType = "Application/excel";
System.Web.HttpContext.Current.Response.WriteFile(localUrl);
System.Web.HttpContext.Current.Response.End();
}
}
}
}
/// <summary>
/// DataGridView导出到Excel文件
/// </summary>
/// <param name="dtSource">源DataTGridview</param>
/// <param name="strHeaderText">表头文本</param>
/// <param name="strFileName">保存位置</param>
public static void DataGridViewToExcel(DataGridView myDgv, string strHeaderText, string strFileName)
{
using (MemoryStream ms = DataGridViewToExcel(myDgv, strHeaderText))
{
if (ms != null)
{
using (FileStream fs = new FileStream(System.Web.HttpContext.Current.Server.MapPath("~/" + DateTime.Now.ToString("yyyymmdd") + ""), FileMode.Create, FileAccess.Write))
{
byte[] data = ms.ToArray();
fs.Write(data, 0, data.Length);
fs.Flush();
}
}
}
}
/// <summary>
/// DataTable导出到Excel的MemoryStream
/// </summary>
/// <param name="dtSource">源DataTable</param>
/// <param name="strHeaderText">表头文本</param>
public static MemoryStream DataTableToExcel(DataTable dtSource, string strHeaderText)
{
if (dtSource == null)
return null;
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet();
#region 右击文件 属性信息
{
DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
dsi.Company = "NPOI";
workbook.DocumentSummaryInformation = dsi;
SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
si.Author = "文件作者信息"; //填加xls文件作者信息
si.ApplicationName = "创建程序信息"; //填加xls文件创建程序信息
si.LastAuthor = "最后保存者信息"; //填加xls文件最后保存者信息
si.Comments = "作者信息"; //填加xls文件作者信息
si.Title = "标题信息"; //填加xls文件标题信息
si.Subject = "主题信息";//填加文件主题信息
si.CreateDateTime = System.DateTime.Now;
workbook.SummaryInformation = si;
}
#endregion
HSSFCellStyle dateStyle = (HSSFCellStyle)workbook.CreateCellStyle();
HSSFDataFormat format = (HSSFDataFormat)workbook.CreateDataFormat();
dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd");
//取得列宽
int[] arrColWidth = new int[dtSource.Columns.Count];
foreach (DataColumn item in dtSource.Columns)
{
arrColWidth[item.Ordinal] = Encoding.GetEncoding(936).GetBytes(item.ColumnName.ToString()).Length;
}
for (int i = 0; i < dtSource.Rows.Count; i++)
{
for (int j = 0; j < dtSource.Columns.Count; j++)
{
int intTemp = Encoding.GetEncoding(936).GetBytes(dtSource.Rows[i][j].ToString()).Length;
if (intTemp > arrColWidth[j])
{
arrColWidth[j] = intTemp;
}
}
}
int rowIndex = 0;
foreach (DataRow row in dtSource.Rows)
{
#region 新建表,填充表头,填充列头,样式
if (rowIndex == 65535 || rowIndex == 0)
{
int IsExitHead = 0;
if (rowIndex != 0)
{
sheet = (HSSFSheet)workbook.CreateSheet();
}
if (!string.IsNullOrEmpty(strHeaderText))
{
IsExitHead = 1;
#region 表头及样式
{
HSSFRow headerRow = (HSSFRow)sheet.CreateRow(0);
headerRow.HeightInPoints = 25;
headerRow.CreateCell(0).SetCellValue(strHeaderText);
HSSFCellStyle headStyle = (HSSFCellStyle)workbook.CreateCellStyle();
// headStyle.Alignment = CellHorizontalAlignment.CENTER;
HSSFFont font = (HSSFFont)workbook.CreateFont();
font.FontHeightInPoints = 20;
font.Boldweight = 700;
headStyle.SetFont(font);
headerRow.GetCell(0).CellStyle = headStyle;
// sheet.AddMergedRegion(new Region(0, 0, 0, dtSource.Columns.Count - 1));
//headerRow.Dispose();
}
#endregion
}
#region 列头及样式
{
HSSFRow headerRow = (HSSFRow)sheet.CreateRow(0);
HSSFCellStyle headStyle = (HSSFCellStyle)workbook.CreateCellStyle();
//headStyle.Alignment = CellHorizontalAlignment.CENTER;
HSSFFont font = (HSSFFont)workbook.CreateFont();
font.FontHeightInPoints = 10;
font.Boldweight = 700;
headStyle.SetFont(font);
foreach (DataColumn column in dtSource.Columns)
{
headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
headerRow.GetCell(column.Ordinal).CellStyle = headStyle;
//设置列宽
sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256);
}
// headerRow.Dispose();
}
#endregion
rowIndex = 1;
}
#endregion
#region 填充内容
HSSFRow dataRow = (HSSFRow)sheet.CreateRow(rowIndex);
foreach (DataColumn column in dtSource.Columns)
{
HSSFCell newCell = (HSSFCell)dataRow.CreateCell(column.Ordinal);
string drValue = row[column].ToString();
switch (column.DataType.ToString())
{
case "System.Guid"://GUID类型
newCell.SetCellValue(drValue);
break;
case "System.String"://字符串类型
newCell.SetCellValue(drValue);
break;
case "System.DateTime"://日期类型
System.DateTime dateV;
System.DateTime.TryParse(drValue, out dateV);
newCell.SetCellValue(dateV);
newCell.CellStyle = dateStyle;//格式化显示
break;
case "System.Boolean"://布尔型
bool boolV = false;
bool.TryParse(drValue, out boolV);
newCell.SetCellValue(boolV);
break;
case "System.Int16"://整型
case "System.Int32":
case "System.Int64":
case "System.Byte":
int intV = 0;
int.TryParse(drValue, out intV);
newCell.SetCellValue(intV);
break;
case "System.Decimal"://浮点型
case "System.Double":
double doubV = 0;
double.TryParse(drValue, out doubV);
newCell.SetCellValue(doubV);
break;
case "System.DBNull"://空值处理
newCell.SetCellValue("");
break;
default:
newCell.SetCellValue("");
break;
}
}
#endregion
rowIndex++;
}
using (MemoryStream ms = new MemoryStream())
{
workbook.Write(ms);
ms.Flush();
ms.Position = 0;
// sheet.Dispose();
//workbook.Dispose();//一般只用写这一个就OK了,他会遍历并释放所有资源,但当前版本有问题所以只释放sheet
return ms;
}
}
/// <summary>
/// DataTable导出到Excel的MemoryStream
/// </summary>
/// <param name="myDgv">源DataTable</param>
/// <param name="strHeaderText">表头文本</param>
public static MemoryStream DataGridViewToExcel(DataGridView myDgv, string strHeaderText)
{
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet();
#region 右击文件 属性信息
{
DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
dsi.Company = "NPOI";
workbook.DocumentSummaryInformation = dsi;
SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
si.Author = "文件作者信息"; //填加xls文件作者信息
si.ApplicationName = "创建程序信息"; //填加xls文件创建程序信息
si.LastAuthor = "最后保存者信息"; //填加xls文件最后保存者信息
si.Comments = "作者信息"; //填加xls文件作者信息
si.Title = "标题信息"; //填加xls文件标题信息
si.Subject = "主题信息";//填加文件主题信息
si.CreateDateTime = System.DateTime.Now;
workbook.SummaryInformation = si;
}
#endregion
HSSFCellStyle dateStyle = (HSSFCellStyle)workbook.CreateCellStyle();
HSSFDataFormat format = (HSSFDataFormat)workbook.CreateDataFormat();
dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd");
//取得列宽
int[] arrColWidth = new int[myDgv.Columns.Count];
foreach (DataGridViewColumn item in myDgv.Columns)
{
arrColWidth[item.Index] = Encoding.GetEncoding(936).GetBytes(item.HeaderText.ToString()).Length;
}
for (int i = 0; i < myDgv.Rows.Count; i++)
{
for (int j = 0; j < myDgv.Columns.Count; j++)
{
int intTemp = Encoding.GetEncoding(936).GetBytes(myDgv.Rows[i].Cells[j].ToString()).Length;
if (intTemp > arrColWidth[j])
{
arrColWidth[j] = intTemp;
}
}
}
int rowIndex = 0;
foreach (DataGridViewRow row in myDgv.Rows)
{
#region 新建表,填充表头,填充列头,样式
if (rowIndex == 65535 || rowIndex == 0)
{
if (rowIndex != 0)
{
sheet = (HSSFSheet)workbook.CreateSheet();
}
#region 表头及样式
{
HSSFRow headerRow = (HSSFRow)sheet.CreateRow(0);
headerRow.HeightInPoints = 25;
headerRow.CreateCell(0).SetCellValue(strHeaderText);
HSSFCellStyle headStyle = (HSSFCellStyle)workbook.CreateCellStyle();
// headStyle.Alignment = CellHorizontalAlignment.CENTER;
HSSFFont font = (HSSFFont)workbook.CreateFont();
font.FontHeightInPoints = 20;
font.Boldweight = 700;
headStyle.SetFont(font);
headerRow.GetCell(0).CellStyle = headStyle;
// sheet.AddMergedRegion(new Region(0, 0, 0, dtSource.Columns.Count - 1));
//headerRow.Dispose();
}
#endregion
#region 列头及样式
{
HSSFRow headerRow = (HSSFRow)sheet.CreateRow(1);
HSSFCellStyle headStyle = (HSSFCellStyle)workbook.CreateCellStyle();
//headStyle.Alignment = CellHorizontalAlignment.CENTER;
HSSFFont font = (HSSFFont)workbook.CreateFont();
font.FontHeightInPoints = 10;
font.Boldweight = 700;
headStyle.SetFont(font);
foreach (DataGridViewColumn column in myDgv.Columns)
{
headerRow.CreateCell(column.Index).SetCellValue(column.HeaderText);
headerRow.GetCell(column.Index).CellStyle = headStyle;
//设置列宽
sheet.SetColumnWidth(column.Index, (arrColWidth[column.Index] + 1) * 256);
}
// headerRow.Dispose();
}
#endregion
rowIndex = 2;
}
#endregion
#region 填充内容
HSSFRow dataRow = (HSSFRow)sheet.CreateRow(rowIndex);
if (row.Index > 0)
{
foreach (DataGridViewColumn column in myDgv.Columns)
{
HSSFCell newCell = (HSSFCell)dataRow.CreateCell(column.Index);
string drValue = myDgv[column.Index, row.Index - 1].Value.ToString();
switch (column.ValueType.ToString())
{
case "System.String"://字符串类型
newCell.SetCellValue(drValue);
break;
case "System.DateTime"://日期类型
System.DateTime dateV;
System.DateTime.TryParse(drValue, out dateV);
newCell.SetCellValue(dateV);
newCell.CellStyle = dateStyle;//格式化显示
break;
case "System.Boolean"://布尔型
bool boolV = false;
bool.TryParse(drValue, out boolV);
newCell.SetCellValue(boolV);
break;
case "System.Int16"://整型
case "System.Int32":
case "System.Int64":
case "System.Byte":
int intV = 0;
int.TryParse(drValue, out intV);
newCell.SetCellValue(intV);
break;
case "System.Decimal"://浮点型
case "System.Double":
double doubV = 0;
double.TryParse(drValue, out doubV);
newCell.SetCellValue(doubV);
break;
case "System.DBNull"://空值处理
newCell.SetCellValue("");
break;
default:
newCell.SetCellValue("");
break;
}
}
}
else
{ rowIndex--; }
#endregion
rowIndex++;
}
using (MemoryStream ms = new MemoryStream())
{
workbook.Write(ms);
ms.Flush();
ms.Position = 0;
// sheet.Dispose();
//workbook.Dispose();//一般只用写这一个就OK了,他会遍历并释放所有资源,但当前版本有问题所以只释放sheet
return ms;
}
}
/// <summary>读取excel
/// 默认第一行为标头
/// </summary>
/// <param name="strFileName">excel文档路径</param>
/// <returns></returns>
public static DataTable Import(string strFileName)
{
DataTable dt = new DataTable();
HSSFWorkbook hssfworkbook;
using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
{
hssfworkbook = new HSSFWorkbook(file);
}
HSSFSheet sheet = (HSSFSheet)hssfworkbook.GetSheetAt(0);
System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
HSSFRow headerRow = (HSSFRow)sheet.GetRow(0);
int cellCount = headerRow.LastCellNum;
for (int j = 0; j < cellCount; j++)
{
HSSFCell cell = (HSSFCell)headerRow.GetCell(j);
dt.Columns.Add(cell.ToString());
}
for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)
{
HSSFRow row = (HSSFRow)sheet.GetRow(i);
DataRow dataRow = dt.NewRow();
for (int j = row.FirstCellNum; j < cellCount; j++)
{
if (row.GetCell(j) != null)
dataRow[j] = row.GetCell(j).ToString();
}
dt.Rows.Add(dataRow);
}
return dt;
}
#endregion
#region Excel文件导成Datatable
// <summary>
/// Excel文件导成Datatable
/// </summary>
/// <param name="strFilePath">Excel文件目录地址</param>
/// <param name="strTableName">Datatable表名</param>
/// <param name="iSheetIndex">Excel sheet index</param>
/// <returns></returns>
public static DataTable XlSToDataTable(string strFilePath, string strTableName)
{
string strExtName = Path.GetExtension(strFilePath);
DataTable dt = new DataTable();
try
{
if (!string.IsNullOrEmpty(strTableName))
{
dt.TableName = strTableName;
}
if (strExtName.Equals(".xls") || strExtName.Equals(".xlsx"))
{
using (FileStream file = new FileStream(strFilePath, FileMode.Open, FileAccess.Read))
{
IWorkbook workbook;
if (strExtName.Equals(".xlsx"))
{
workbook = new XSSFWorkbook(file);
}
else if (strExtName.Equals(".xls"))
{
workbook = new HSSFWorkbook(file);
}
else { workbook = null; }
ISheet sheet = workbook.GetSheetAt(0);
IRow header = sheet.GetRow(sheet.FirstRowNum);
List<int> columns = new List<int>();
for (int i = 0; i < header.LastCellNum; i++)
{
object obj = header.GetCell(i);
if (obj == null || obj.ToString() == string.Empty)
{
dt.Columns.Add(new DataColumn("Columns" + i.ToString()));
}
else
dt.Columns.Add(new DataColumn(obj.ToString()));
columns.Add(i);
}
//数据
for (int i = sheet.FirstRowNum + 1; i <= sheet.LastRowNum; i++)
{
DataRow dr = dt.NewRow();
bool hasValue = false;
foreach (int j in columns)
{
dr[j] = sheet.GetRow(i).GetCell(j);
if (dr[j] != null && dr[j].ToString() != string.Empty)
{
hasValue = true;
}
}
if (hasValue)
{
dt.Rows.Add(dr);
}
}
}
return dt;
}
}
catch (Exception ex)
{
Log.SaveException(ex);
}
return dt;
}
#endregion
}
@skateweb: 少给了一个类 懒的重新弄一个包了
@筱浬:这么长 哪里是重点啊 压缩包里面都是aspx文件的 打不开...
@skateweb: 你用记事本打开.cs后缀的文件,然后找到导出的代码 把我上面那个类新建一个帮助类
@筱浬: 你这些代码 和我的问题没有任何关系啊 ,我的这个异常如何解决啊擦擦擦getOutputStream() has already been called for this response,就是他 解决就好
@skateweb: 我的意思是,你换这种方案看看会不会有这个异常... 这个异常我不知道
@筱浬: 我试试
@筱浬: 你那个 我看不懂啊 我就是一个下载功能,很简单的 你这些代码好复杂啊 擦 不会用
@skateweb: 我给你看图片吧 我就几行代码
@skateweb: 我觉得很简单啊。。。 你想办法弄一个DataTable 其他的就直接调用