62,074
社区成员
发帖
与我相关
我的任务
分享
public static string toExcel(HttpContext context)
{
XTBG_Entity.Person[] person = null;//我用的是实体数组,List一样
StringBuilder mStr = new StringBuilder();
int type = int.Parse(context.Request.Form["type"]);
int PageIndex = int.Parse(context.Request.Form["bbpageIndex"]);
int PageSize = int.Parse(context.Request.Form["pageSize"]);
mStr.Append("名字\t");
mStr.Append("姓氏\t");
mStr.Append("单位\t");
mStr.Append("移动电话\t");
mStr.Append("固定电话\t");
mStr.Append("电子邮箱\n");
if (type == 1)
{
int algId = int.Parse(context.Request.Form["AlgId"]);
person = XTBG_Logic.ALG.Alg.GetAllMembersByGroup(algId, PageIndex, PageSize);
}
else if (type == 2)
{
string TxName = context.Request.Form["TxName"].ToString();
person = XTBG_Logic.ALG.Alg.GetPersonByKeyword(TxName, PageIndex, PageSize);
}
foreach (XTBG_Entity.Person p in person)
{
mStr.Append(p.LastName + "\t");
mStr.Append(p.FirstName + "\t");
mStr.Append(p.OfficeName + "\t");
mStr.Append(p.PhoneNo + "\t");
mStr.Append(p.HomeTel + "\t");
mStr.Append(p.Email + "\n");
}
return XTBG_Entity.Tools.Excel.StringToExcel("自定义分组.xls", mStr.ToString(), context).ToString();//调用的是下面类中的方法
}
public class Excel
{
#region 将生成的Excel字符串导出
/// <summary>
/// 将生成的Excel字符串导出
/// </summary>
/// <param name="fileName"></param>
/// <param name="strExcel"></param>
/// <param name="context"></param>
/// <returns>-1 服务器不允许访问,其它 excel文件地址</returns>
public static string StringToExcel(string fileName, string strExcel, HttpContext context)
{
string IdentityAnalogue = System.Configuration.ConfigurationManager.AppSettings["IdentityAnalogue"];
string[] strArray = IdentityAnalogue.Split(';');
IdentityAnalogue IA = new IdentityAnalogue();
bool bo = IA.impersonateValidUser(strArray[0], strArray[1], strArray[2]);
if (!bo)
{
return "-1";
}
//if (bo)
//{
// return "-1";
//}
string urlPath = "http://" + context.Request.Url.Authority + context.Request.ApplicationPath + "/Excel";
string ExcelFolder = context.Request.PhysicalApplicationPath + "\\Excel";
DirectoryInfo m_dir = new System.IO.DirectoryInfo(ExcelFolder);
if (!m_dir.Exists)
{
m_dir.Create();
}
if ((m_dir.Attributes & FileAttributes.ReadOnly) != 0)
{
m_dir.Attributes = FileAttributes.Normal;
System.Security.AccessControl.DirectorySecurity dirsecurity = m_dir.GetAccessControl();
System.Security.AccessControl.FileSystemAccessRule fsa = new System.Security.AccessControl.FileSystemAccessRule(strArray[0], System.Security.AccessControl.FileSystemRights.FullControl, System.Security.AccessControl.AccessControlType.Allow);
dirsecurity.AddAccessRule(fsa);
}
FileInfo[] m_files = m_dir.GetFiles();
for (int i = 0; i < m_files.Length; i++)
{
if (m_files[i].LastWriteTime.AddDays(1) < System.DateTime.Now)
{
m_files[i].Delete();
}
}
System.IO.StreamWriter sw = new System.IO.StreamWriter(ExcelFolder + "\\" + fileName, false, System.Text.Encoding.Default);
sw.Write(strExcel);
sw.Flush();
sw.Close();
IA.undoImpersonation();
return urlPath + "/" + fileName;
}
#endregion
#region 保存Excel文件
/// <summary>
/// 保存Excel文件
/// </summary>
/// <param name="file"></param>
/// <param name="fileName"></param>
/// <returns></returns>
public static string SaveExcel(HttpPostedFile file, string fileName, HttpContext context)
{
string IdentityAnalogue = System.Configuration.ConfigurationManager.AppSettings["IdentityAnalogue"];
string[] strArray = IdentityAnalogue.Split(';');
IdentityAnalogue IA = new IdentityAnalogue();
bool bo = IA.impersonateValidUser(strArray[0], strArray[1], strArray[2]);
if (!bo)
{
return "-1";
}
string urlPath = "http://" + context.Request.Url.Authority + context.Request.ApplicationPath + "/Excel";
string ExcelFolder = context.Request.PhysicalApplicationPath + "Excel";
DirectoryInfo m_dir = new System.IO.DirectoryInfo(ExcelFolder);
if (!m_dir.Exists)
{
m_dir.Create();
}
if ((m_dir.Attributes & FileAttributes.ReadOnly) != 0)
{
m_dir.Attributes = FileAttributes.Normal;
System.Security.AccessControl.DirectorySecurity dirsecurity = m_dir.GetAccessControl();
System.Security.AccessControl.FileSystemAccessRule fsa = new System.Security.AccessControl.FileSystemAccessRule(strArray[0], System.Security.AccessControl.FileSystemRights.FullControl, System.Security.AccessControl.AccessControlType.Allow);
dirsecurity.AddAccessRule(fsa);
}
FileInfo[] m_files = m_dir.GetFiles();
for (int i = 0; i < m_files.Length; i++)
{
if (m_files[i].LastWriteTime.AddDays(1) < System.DateTime.Now && m_files[i].Extension == ".xls")
{
m_files[i].Delete();
}
}
file.SaveAs(ExcelFolder + "\\" + fileName);
IA.undoImpersonation();
return ExcelFolder + "\\" + fileName;
}
#endregion
}
}
/// <summary>
/// 定义导出Excel的函数
/// </summary>
/// <param name="FileType"></param>
/// <param name="FileName"></param>
private void Export(string FileType, string FileName)
{
GridView1.AllowPaging = false;
GridView1.DataBind();
Response.Clear();
Response.Buffer = true;
Response.Charset = "GB2312";
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString());
Response.ContentType = FileType;
this.EnableViewState = false;
GridView1.Columns[GridView1.Columns.Count - 1].Visible = false;
GridView1.Columns[GridView1.Columns.Count - 2].Visible = false;
StringWriter tw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
GridView1.RenderControl(hw);
Response.Write(tw.ToString());
Response.End();
}
protected void Button1_Click(object sender, EventArgs e)
{
Export("application/ms-excel", "Employee information.xls");
GridView1.AllowPaging = true;
}
上面那些调用下面这个方法:
string fileName = Server.MapPath("~/Resource/ExcelFolder/") + GetDateString() + ".xls";
InitExcelFile(Response, fileName);
private void InitExcelFile(HttpResponse res, string fileName)
{
res.Clear();
res.AppendHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
res.ContentType = "application/ms-excel";
res.WriteFile(fileName);
//res.End();
string excelFileName = fileName.Substring(fileName.LastIndexOf("\\") + 1);
Response.Redirect("/Resource/ExcelFolder/" + excelFileName, true);
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Specialized;
using System.Collections;
namespace WebLibrary
{
/// <summary>
/// 导出到excel文件。
/// </summary>
public class ExcelHelper
{
public static string GetXlsLine(params object[] aoField)
{
StringCollection items = new StringCollection();
for (int i = 0; i < aoField.Length; i++)
{
items.Add(aoField[i].ToString());
}
return GetXlsLine(items);
}
public static string GetXlsLine(ICollection items)
{
string sLineText = string.Empty;
foreach (Object item in items)
{
if (item != null) sLineText = sLineText + "\"" + item.ToString().Replace("\"", "") + "\"\t";
}
if (sLineText != string.Empty) sLineText = Left2(sLineText, 1);
return sLineText + "\r\n";
}
public static String[][] Parse(String sText)
{
if (sText == null || sText.Length == 0) return new String[0][] { };
String st = string.Empty;
ArrayList asLineText = new ArrayList(); // 行集合。其元素为行
ArrayList asCellText = new ArrayList(); // 单元格集合。其元素为一个单元格
bool bBeginWithQuote = false;
int iMaxColumns = 0;
for (int i = 0; i < sText.Length; i++)
{
char ch = sText[i];
if (ch == '\r' || ch == '\n')
{
if (bBeginWithQuote)
{
st += ch;
}
else
{
if (ch == '\r' && i + 1 < sText.Length && sText[i + 1] == '\n') i++;
asCellText.Add(st);
st = string.Empty;
bBeginWithQuote = false;
iMaxColumns = (asCellText.Count > iMaxColumns ? asCellText.Count : iMaxColumns);
asLineText.Add(asCellText);
st = string.Empty;
asCellText = new ArrayList();
}
}
else if (ch == '\"')
{
if (bBeginWithQuote)
{
i++;
if (i >= sText.Length)
{
asCellText.Add(st);
st = string.Empty;
bBeginWithQuote = false;
}
else
{
ch = sText[i];
if (ch == '\"')
{
st += ch;
}
else if (ch == ',')
{
asCellText.Add(st);
st = string.Empty;
bBeginWithQuote = false;
}
else if (ch == '\r' || ch == '\n')
{
asCellText.Add(st);
st = string.Empty;
bBeginWithQuote = false;
iMaxColumns = (asCellText.Count > iMaxColumns ? asCellText.Count : iMaxColumns);
asLineText.Add(asCellText);
st = string.Empty;
asCellText = new ArrayList();
if (ch == '\r' && i + 1 < sText.Length && sText[i + 1] == '\n') i++;
}
else
{
throw new Exception("当字段以双引号开始时,禁止字段中存在单个双引号。字段号" + (asCellText.Count + 1) + ",列号:" + i);
}
}
}
else if (st.Length == 0)
{
bBeginWithQuote = true;
}
else
{
throw new Exception("双引号禁止存在于非双引号开始的字段。字段号:" + (asCellText.Count + 1));
}
}
else if (ch == ',')
{
if (bBeginWithQuote)
{
st += ch;
}
else
{
asCellText.Add(st);
st = string.Empty;
bBeginWithQuote = false;
}
}
else
{
st += ch;
}
}
if (st.Length != 0)
{
if (bBeginWithQuote)
{
throw new Exception("最后一个字段以双引号开始,但未以双引号结束。");
}
else
{
asCellText.Add(st);
iMaxColumns = (asCellText.Count > iMaxColumns ? asCellText.Count : iMaxColumns);
asLineText.Add(asCellText);
}
}
String[][] asReturn = new String[asLineText.Count][];
for (int i = 0; i < asReturn.Length; i++)
{
asCellText = (ArrayList)asLineText[i];
asReturn[i] = new String[iMaxColumns];
for (int j = 0; j < iMaxColumns; j++)
{
asReturn[i][j] = asCellText[j].ToString();
}
}
return asReturn;
}
public static string Left2(string sInput, int iRightLength)
{
if (sInput == string.Empty) return string.Empty;
return sInput.Substring(0, sInput.Length - iRightLength);
}
}
}
FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.GetEncoding("gb2312"));
list = sdBll.GetPageList();
sw.Write(ExcelHelper.GetXlsLine("电池组信息", "电池组电流", "充放电状态", "电池组容量", "数据获取时间"));
foreach (Model.StringData model in list)
{
sw.Write(ExcelHelper.GetXlsLine(mBll.GetMenuName(model.ID), model.CHARGECURRENT / 10.0, model.STATE == 0 ? "否" : "是", model.SOC, model.DataDATE));
}
" +"文件标题"+ " | " + "档案类别" + " | " +"发文日期" + " | " +"文件链接" + " | " +"备注" + " | " + dt.Rows[i]["FileName"]+ " | "); resp.Write("" +dt.Rows[i]["type"]+ " | "); resp.Write("" + dt.Rows[i]["fromtime"].ToString()+ " | "); resp.Write("" + dt.Rows[i]["url"]+ " | "); resp.Write("" + dt.Rows[i]["beizhu"]+ " | "); resp.Write(""); } resp.Write("
---|