标签:
Reports.aspx :
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>资料文库管理</title>
<script src="../Scripts/boot.js" type="text/javascript"></script>
<script src="../Scripts/Utility.js" type="text/javascript"></script>
<script src="../Scripts/anychart_files/js/anychart.js" type="text/javascript"></script>
<link href="../css/main.css" rel="stylesheet" type="text/css" />
<style type="text/css">
body
{
margin: 0;
padding: 0;
border: 0;
width: 100%;
height: 1200px;
overflow: visible;
}
</style>
</head>
<body>
<div class="mini-panel" style="width: 100%;" showheader="false" showtoolbar="false"
showclosebutton="false" showfooter="false">
<div class="contentLeft1" style="min-height: 1150px; width: 170px; margin-left: 0px;">
<div class="contentLeftTitle" style="width: 170px;">
<div class="contentLeftTitleIcon">
</div>
<div>
资料文库</div>
</div>
<ul id="ReportType" class="mini-tree" url="ReportManage.ashx?method=LoadTree&selType=<%=selType %>"
style="padding: 5px; height: 1100px;" showtreeicon="false" textfield="text" idfield="id"
parentfield="pid" resultastree="false" checkrecursive="true" expandonload="true"
scroll="false" allowselect="true" enablehottrack="false" onnodeselect="onnodeselect">
</ul>
<div class="clearboth">
</div>
</div>
<div class="contentRight" style="min-height: 1150px; width: 790px;">
<div class="contentRightTitle" style="width: 790px;">
<div class="contentRightTableIcon">
</div>
<div>
资料文库管理</div>
</div>
<div class="contentRightButtons">
<input type="button" id="Export" onclick="Export()" value="导出" />
</div>
<div style="margin-top: 2px; width: 790px;">
<div id="datagrid1" class="mini-datagrid" style="width: 100%; height: 100%; min-height: 1080px;"
allowcellwrap="true" idfield="id" allowresize="true" allowresize="true" showpager="true"
multiselect="true" pagesize="50" allowalternating="true" pageindexfield="Index"
pagesizefield="Size" url="ReportManage.ashx?method=ReportDataMan&menutype=<%=num %>">
<div property="columns">
<div field="ID" name="ID" width="100" align="center" headeralign="center">
ID
</div>
<div field="Number" width="40" align="center" headeralign="center">
序号
</div>
<div field="XXBT" width="200" align="center" headeralign="center" renderer="onDownReport">
标题
</div>
<div field="TypeNAME" width="60" align="center" headeralign="center">
类别
</div>
<div field="XXSJ" width="90" align="center" headeralign="center">
完成时间
</div>
<div field="USERID" width="60" align="center" headeralign="center" renderer="onReportUSER">
录入人
</div>
</div>
</div>
</div>
<div>
</div>
<iframe id="exportIFrame" style="display: none;"></iframe>
</div>
</div>
</body>
</html>
<script type="text/javascript">
var num = 0;
mini.parse();
var selType = "<%=selType %>";
var menutype = "<%=num %>";
function Export() {
var grid = mini.get("datagrid1");
var Size = grid.pager.pageSize;
var Index = grid.pager.pageIndex;
var menutype = "<%=num %>";
var url = "ReportManage.ashx?method=Export&pageSize=" + Size + "&pageIndex=" + Index + "&menutype=" + menutype;
var exportIFrame = document.getElementById("exportIFrame"); exportIFrame.src = url; }
</style>
Reports.aspx.cs :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CNPC.PlatForm.BLL;
using System.Web.Services; using System.Data;
namespace CNPC.PlatForm.Web.Reports {
public partial class Reports : System.Web.UI.Page
{
public int num = 0;
public string selType, NeiID, WaiID = "";
protected void Page_Load(object sender, EventArgs e)
{
ReportBLL datashowBll = new ReportBLL();
selType = Request["selType"];
if (selType == "35") { num = 1; }
}
}
}
ReportManage.ashx :
using System;
using System.Data;
using System.Drawing;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Web;
using System.Collections;
using CNPC.PlatForm.BLL;
using System.IO;
using CNPC.PlatForm.Entity;
using System.Collections.Generic;
using CNPC.PlatForm.Dal;
using Microsoft.Office.Interop.Excel;
using DataTable = System.Data.DataTable;
using CNPC.Common.BaseHelper;
namespace CNPC.PlatForm.Web.Reports {
/// <summary>
/// ReportManage1 的摘要说明
/// </summary>
public class ReportManage1 : DataProcess {
protected override object processQuery(HttpContext context, out bool hasError)
{
string method = context.Request["method"];
hasError = false;
switch (method) {
//导出全部字段
case "Export":
return Export(context);
default:
return null;
}
}
#region 导出
public string Export(HttpContext context) {
StringBuilder sBuilder = new StringBuilder();
sBuilder.Append("<table cellspacing=\"0\" cellpadding=\"5\" rules=\"all\" border=\"1\">");
StringBuilder sHead = new StringBuilder();
sHead.Append("<tr style=\"font-weight: bold; white-space: nowrap; text-align=center;\">");
string[] columnName = { "出处", "创建时间", "标题", "报告分类", "ID", "分类名称", "用户编码", "信息时间", "修改时间", "状态" };
for (int i = 0; i < columnName.Length; i++) {
sHead.AppendFormat("<td>{0}</td>", columnName[i]);
}
sHead.Append("</tr>");
//获取要导出的数据(DataTable)
DataTable data= bll.getdatetable();
if (data== null)
{
return "null";
}
StringBuilder sContent = new StringBuilder();
for (int i = 0; i < data.Rows.Count; i++)
{
sContent.Append("<tr align=\"center\">");
sContent.AppendFormat("<td>{0}</td>", data.Rows[i]["CHUCHU"]);
sContent.AppendFormat("<td>{0}</td>", data.Rows[i]["CJSJ"]);
sContent.AppendFormat("<td>{0}</td>", data.Rows[i]["XXBT"]);
sContent.AppendFormat("<td>{0}</td>", data.Rows[i]["TYPEID"]);
sContent.AppendFormat("<td>{0}</td>", data.Rows[i]["ID"]);
sContent.AppendFormat("<td>{0}</td>", data.Rows[i]["TypeNAME"]);
sContent.AppendFormat("<td>{0}</td>", data.Rows[i]["USERID"]);
sContent.AppendFormat("<td>{0}</td>", data.Rows[i]["XXSJ"]);
sContent.AppendFormat("<td>{0}</td>", data.Rows[i]["XGSJ"]);
sContent.AppendFormat("<td>{0}</td>", data.Rows[i]["Status"]);
sContent.Append("</tr>");
}
sBuilder.Append(sHead);
sBuilder.Append(sContent);
sBuilder.Append("</table>");
ExcelHelper excelHelper = new ExcelHelper();
bool result = excelHelper.saveAsExcel(sBuilder.ToString(), "资料文库");
return "";
}
#endregion
}
}
ExcelHelper.cs :
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Web;
using System.Text;
using CNPC.Common.DataHelper;
namespace CNPC.Common.BaseHelper {
/// <summary>
/// Excel帮助类
/// </summary>
public class ExcelHelper {
public ExcelHelper()
{ ;}
#region 应用数据库配置
/// <summary>
/// SqlServer数据库连接字符串
/// </summary>
public static string SqlConnectionString
{
get
{
//获取数据库连接字符串
string sqlConnectionString = StringUtils.NotNullStr(ConfigurationManager.ConnectionStrings[Constants.SQLCONNECTIONSTRING], string.Empty);
//判断连接字符串是否为空
if (string.IsNullOrEmpty(sqlConnectionString))
{
return string.Empty;
}
else
{
//获取连接字符串是否加密
bool isConStringEncrypt = StringUtils.ToInt(ConfigurationManager.AppSettings[Constants.CONSTRINGENCRYPT]) == 1 ? true : false;
//判断是否对字符串加密
if (isConStringEncrypt)
sqlConnectionString = DESEncrypt.Decrypt(sqlConnectionString);
return sqlConnectionString;
}
}
}
#endregion
/// <summary>
/// 返回非空字符串
/// </summary>
/// <param name="canNullStr"></param>
/// <param name="defaultStr"></param>
/// <returns></returns>
public static string NotNullStr(object canNullStr, string defaultStr)
{
try
{
if ((canNullStr == null) || (canNullStr is DBNull))
{
if (defaultStr != null)
{
return defaultStr;
}
return "";
}
return Convert.ToString(canNullStr);
}
catch
{
return defaultStr;
}
}
#region 一般配置
/// <summary>
/// 导入Excel时,服务器的临时文件夹
/// </summary>
public static string UploadTempFolderPath
{
get { return NotNullStr(ConfigurationManager.AppSettings[Constants.UPLOADTEMPFOLDERPATH], string.Empty); }
}
#endregion
#region 导入Excel
/// <summary>
/// 上传文件(true:上传成功;false:上传失败)
/// </summary>
/// <param name="postedFile">上传文件控件</param>
/// <param name="uploadPath">上传路径[ref]</param>
/// <returns></returns>
public bool UploadExcel(HttpPostedFile postedFile, ref string uploadPath)
{
//获取上传路径
uploadPath = UploadTempFolderPath;
uploadPath += "/" + Guid.NewGuid();
uploadPath = HttpContext.Current.Server.MapPath(uploadPath);
//上传文件
try
{
postedFile.SaveAs(uploadPath);
return true;
}
catch
{
return false;
}
}
/// <summary>
/// 获取excel的schema名称集合(返回List[string]集合)
/// </summary>
/// <param name="excelPath">excel路径</param>
/// <returns></returns>
public List<string> GetSchemaNameList(string excelPath)
{
//获取连接字符串
string oledbConString = GetConString(excelPath);
//如果Oledb连接字符串为空
if (string.IsNullOrEmpty(oledbConString))
return null;
else
{
using (OleDbConnection con = new OleDbConnection(oledbConString))
{
try
{
con.Open();//打开连接
//读取Excel中的数据
DataTable dt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
//关闭连接
con.Close();
//判断dt是否为空
if (dt == null)
return null;
else
{
//定以存放schema的容器
List<string> list = new List<string>();
//遍历dt
foreach (DataRow dr in dt.Rows)
{
string tableName = dr["TABLE_NAME"].ToString();
int tableNameLength = tableName.Length;
list.Add(tableName.Substring(0, tableNameLength - 1));
}
return list;
}
}
catch { return null; }
}
}
}
/// <summary>
/// 获取excel的数据(返回DataTable)
/// </summary>
/// <param name="schemaName">schema名称</param>
/// <param name="startRow">开始行</param>
/// <param name="endRow">结束行</param>
/// <param name="excelPath">excel路径</param>
/// <returns></returns>
public DataTable GetExcelData(string schemaName, int startRow, int endRow, string excelPath)
{
try
{
//根据schema名称和excel路径获取当前schema的数据
DataTable dt = GetExcelData(schemaName, excelPath);
if (dt == null)
return null;
else
{
//判断选定的读取行是否超过索引上限
if (dt.Rows.Count < endRow || startRow > endRow)
return null;
else
{
//创建新的DataTable
DataTable newDt = new DataTable();
//设置newDt的列
for (int i = 0; i < dt.Columns.Count; i++)
{
DataColumn dc = new DataColumn(i.ToString());
newDt.Columns.Add(dc);
}
//获取dt的列数
int columnCount = dt.Columns.Count;
//遍历DataTable的数据
for (int i = startRow - 1; i <= endRow - 1; i++)
{
//实例化对象数组,长度为DataTable的列数量
object[] obj = new object[columnCount];
for (int j = 0; j < columnCount; j++)
{
obj.SetValue(dt.Rows[i][j], j);
}
newDt.Rows.Add(obj);
}
//删除临时文件
DeleteExcel(excelPath);
return newDt;
}
}
}
catch
{
return null;
}
}
/// <summary>
/// 根据schema名称和excel路径获取当前schema的数据
/// </summary>
/// <param name="schemaName">schema名称</param>
/// <param name="excelPath">excel路径</param>
/// <returns></returns>
private DataTable GetExcelData(string schemaName, string excelPath)
{
//获取连接字符串
string oledbConString = GetConString(excelPath);
//如果Oledb连接字符串为空
if (string.IsNullOrEmpty(oledbConString))
return null;
else
{
using (OleDbConnection con = new OleDbConnection(oledbConString))
{
try
{
string sqlString = "select * from [" + schemaName + "$]";
DataSet ds = new DataSet();
OleDbDataAdapter da = new OleDbDataAdapter(sqlString, con);
da.Fill(ds);
return ds.Tables[0];
}
catch { return null; }
}
}
}
/// <summary>
/// 获取连接字符串
/// </summary>
/// <param name="excelPath">excel路径</param>
/// <returns></returns>
private string GetConString(string excelPath)
{
string connString = SqlConnectionString;
connString = string.Format(connString, excelPath);
return connString;
}
/// <summary>
/// 根据文件路径删除文件
/// </summary>
/// <param name="ExcelPath"></param>
private void DeleteExcel(string excelPath)
{
//判断文件是否存在
if (File.Exists(excelPath))
{
//删除文件
File.Delete(excelPath);
}
}
#endregion
#region 将html内容另存为Excel
/// <summary>
/// 将html内容另存为Excel
/// </summary>
/// <param name="content">html格式的内容字符串</param>
/// <param name="xlsFile">要保存的Excel文件名</param>
/// <returns></returns>
public bool saveAsExcel(string content, string xlsFile)
{
try
{
string html = "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=gb2312\">" + content;
System.Web.HttpContext curContext = System.Web.HttpContext.Current;
curContext.Response.Buffer = true;
curContext.Response.Clear();
curContext.Response.Charset = "GB2312";
if (curContext.Request.UserAgent.Contains("MSIE") || curContext.Request.UserAgent.Contains("msie"))
{
// 如果客户端使用 Microsoft Internet Explorer,则需要编码
// 如果使用 fileName =Server.UrlEncode(fileName); 则会出现上文中出现的情况
xlsFile = toHexString(xlsFile);
}
curContext.Response.AppendHeader("Content-Disposition", "attachment;filename=" + xlsFile + ".xls");
curContext.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
//设置输出流为简体中文
curContext.Response.ContentType = "application/ms-excel";
//设置输出文件类型为excel文件。
curContext.Response.Write(html);
curContext.Response.Flush();
curContext.Response.Clear();
//curContext.Response.End();
curContext.ApplicationInstance.CompleteRequest();
}
catch (Exception ex)
{
return false;
}
return true;
}
// 为字符串中的非英文字符编码
string toHexString(string s) {
char[] chars = s.ToCharArray();
StringBuilder builder = new StringBuilder();
for (int index = 0; index < chars.Length; index++)
{
bool bEncode = needToEncode(chars[index]);
if (bEncode)
{
string encodedString = toHexString(chars[index]);
builder.Append(encodedString);
}
else
{
builder.Append(chars[index]);
}
}
return builder.ToString();
}
//指定 一个字符是否应该被编码
bool needToEncode(char chr)
{
string reservedChars = "$-_.+!*‘(),@=&";
if (chr > 127)
return true;
if (char.IsLetterOrDigit(chr) || reservedChars.IndexOf(chr) >= 0)
return false;
return true;
}
// 为非英文字符串编码
string toHexString(char chr)
{
UTF8Encoding utf8 = new UTF8Encoding();
byte[] encodedBytes = utf8.GetBytes(chr.ToString());
StringBuilder builder = new StringBuilder();
for (int index = 0; index < encodedBytes.Length; index++)
{
builder.AppendFormat("%{0}", Convert.ToString(encodedBytes[index], 16));
}
return builder.ToString();
}
#endregion
}
}
标签:
原文地址:http://www.cnblogs.com/lk516924/p/5551842.html