ASP.NET开发简单实用的方法
一、打印和导出
打印和导出EXCEL在目前ASP.NET开发中可以说是必要的,有时候针对不同数据难易程度下,用有效快速的方法是解决办法的有效途径之一。
1.打印
后台:
/// <summary>
/// 调用GOOGLE自带打印格式
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Btn_Printf_Click(object sender, EventArgs e)
{
this.Page.ClientScript.RegisterStartupScript(this.Page.GetType(), "", "<script>printdiv();window.close();</script>", false);//后台打印事件
}
前台:
<script type="text/javascript">
function printdiv() {
bdhtml = window.document.body.innerHTML;
sprnstr = "<!--startprint-->";//开始打印标记
eprnstr = "<!--endprint-->";//结束打印标记
prnhtml = bdhtml.substr(bdhtml.indexOf(sprnstr) + 17);
prnhtml = prnhtml.substring(0, prnhtml.indexOf(eprnstr));
window.document.body.innerHTML = prnhtml;
window.print();
window.document.body.innerHTML = bdhtml;
closeWindow();
}
function closeWindow() {
setTimeout("window.opener=null;window.open('','_self');window.close();", 1000); //打印后延时2秒后跳转
}
</script>
2.导出EXCEL
/// <summary>
/// 导出
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Btn_Output_Click(object sender, EventArgs e)
{
var FileName = DateTime.Now.ToString("yyyy-MM-dd");
System.Data.DataTable dt =需要打印数据;
if (dt != null && dt.Rows.Count > 0)
{
CreateExcel_t(dt, FileName);
}
else
{
Response.Write("<script>alert('【系统提示】暂无数据,请先上传数据!')</script>");
return;
}
}
/// <summary>
/// 生成EXCEL
/// </summary>
/// <param name="dt">数据</param>
/// <param name="FileName">生成EXCEL名称</param>
public void CreateExcel_t(DataTable dt, string FileName)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Charset = "UTF-8";
HttpContext.Current.Response.ContentType = "application/vnd.ms-xls";
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + FileName + "导出EXEL名称.xls");
StringBuilder table = new StringBuilder();
//<tr cospan='2' style='text-align:center;'>EXCEL标题</tr>
table.Append("<table><tr>");
for (int j = 0; j < dt.Columns.Count; j++)
{
table.Append("<td style='text-align:center;'>");
table.Append(dt.Columns[j].Caption.ToString());//表格的标题
table.Append("</td>");
}
table.Append("</tr>");
for (int i = 0; i < dt.Rows.Count; i++)
{
table.Append("<tr>");
for (int j = 0; j < dt.Columns.Count; j++)
{
table.Append("<td style='vnd.ms-excel.numberformat:@'>");
table.Append(dt.Rows[i][j].ToString());
table.Append("</td>");
}
table.Append("</tr>");
}
table.Append("</table>");
HttpContext.Current.Response.Write(table);
HttpContext.Current.Response.End();
}
二、AspNetPager翻页
1.方法一
//在aspx网页中
<%@ Register Assembly="AspNetPager" Namespace="Wuqi.Webdiyer" TagPrefix="webdiyer" %>
<webdiyer:AspNetPager ID="AspNetPager1" runat="server" OnPageChanged="AspNetPager1_PageChanged" PageSize="1" CustomInfoHTML="第 <font color='red'><b>%currentPageIndex%</b></font> 页,共 %PageCount% 页,每页显示 %PageSize% 条记录,共 %RecordCount% 条记录" FirstPageText="第一页" PrevPageText="上一页" NextPageText="下一页" LastPageText="最末页" CustomInfoTextAlign="Center" CssClass="white" ShowCustomInfoSection="Left" AlwaysShow=true SubmitButtonText="Go" PageIndexBoxType="DropDownList" ShowBoxThreshold="10" ShowPageIndexBox="Auto" TextAfterPageIndexBox="页" TextBeforePageIndexBox="转到"></webdiyer:AspNetPager>
//在Page_Load中
AspNetPager1.RecordCount = (int)Cqzxw.SqlData.ExecuteScalar("Select count(*) From 表名");
ShowData();
//在数据绑定时
private void ShowData()
{
DataSet ds =Cqzxw.SqlData.ExecuteDataSet("Select * From 表名", AspNetPager1.PageSize * (AspNetPager1.CurrentPageIndex - 1), AspNetPager1.PageSize);
GridView1.DataSource = ds;
GridView1.DataBind();
}
protected void AspNetPager1_PageChanged(object sender, EventArgs e)
{
ShowData();
}
2.方法二
前端
<div style=" text-align:center; margin-top:10%;">
<webdiyer:AspNetPager ID="AspNetPager2" runat="server" BorderStyle="None" FirstPageText="首页" LastPageText="尾页" NextPageText="下一页" PagingButtonSpacing="30px" OnPageChanged="AspNetPager1_PageChanged" PageSize="6" PrevPageText="上一页" SubmitButtonText="转到"></webdiyer:AspNetPager>
</div>
后端
protected void AspNetPager1_PageChanged(object sender, EventArgs e)
{
//ShowData();
aspnetpager();
}
public void aspnetpager()
{
DataTable dt = 需要打印数据;
string Msg = ToJson(dt);
this.Lab_Count.Text = dt.Rows.Count.ToString();
//设置数量为DataTable的行数
AspNetPager2.RecordCount = dt.Rows.Count;
//分页数据源对象
PagedDataSource pds = new PagedDataSource();
//设置为允许分页
pds.AllowPaging = true;
//设置每一页的大小 (ASPNetPager1.PageSize在控件属性里面设置)
pds.PageSize = this.AspNetPager2.PageSize;
//当前页面索引是 aspnetpager控件页面索引-1,因为后者的CurrentPageIndex是1开始
pds.CurrentPageIndex = this.AspNetPager2.CurrentPageIndex - 1;
//设置PageDataSource的数据源(DataView)
pds.DataSource = dt.DefaultView;
//设置Repeater的数据源(是PageDataSource)
Repeater1.DataSource = pds;
//绑定数据
Repeater1.DataBind();
}
三、编写日志
1.写法一
WriteLog(string.Format(@"参数={0}、参数={1}、参数={2}、参数={3}、参数={4}、参数={5}",对应参数, 对应参数,对应参数, 对应参数, 对应参数, 对应参数));//编写日志方法
2.写法二
WriteLog("提示字符串"+需要传递的参数);
/// <summary>
/// 在本地写入错误日志
/// </summary>
private static readonly object writeFile = new object();
/// <summary>
/// 在本地写入错误日志
/// </summary>
/// <param name="exception"></param>
public static void WriteLog(string debugstr)
{
lock (writeFile)
{
FileStream fs = null;
StreamWriter sw = null;
try
{
//string filename = DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
string filename = DateTime.Now.ToString("yyyy-MM-dd") + ".Log.txt";
//服务器中日志目录
//string folder = HttpContext.Current.Server.MapPath("~/Log");
string folder = AppDomain.CurrentDomain.BaseDirectory + @"Log\";
if (!Directory.Exists(folder))
Directory.CreateDirectory(folder);
fs = new FileStream(folder + "/" + filename, System.IO.FileMode.Append, System.IO.FileAccess.Write);
sw = new StreamWriter(fs, Encoding.UTF8);
sw.WriteLine(DateTime.Now.ToString() + " " + debugstr + "\r\n");
}
finally
{
if (sw != null)
{
sw.Flush();
sw.Dispose();
sw = null;
}
if (fs != null)
{
// fs.Flush();
fs.Dispose();
fs = null;
}
}
}
}
四、DataTable解析Json数据
1.DataTable解析Json数据方法一
/// <summary>
/// DataTable解析Json数据【方法一】
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static string ToJson(DataTable dt)
{
StringBuilder jsonString = new StringBuilder();
jsonString.Append("[");
DataRowCollection drc = dt.Rows;
for (int i = 0; i < drc.Count; i++)
{
jsonString.Append("{");
for (int j = 0; j < dt.Columns.Count; j++)
{
string strKey = dt.Columns[j].ColumnName;
string strValue = drc[i][j].ToString();
Type type = dt.Columns[j].DataType;
jsonString.Append("\"" + strKey + "\":");
strValue = StringFormat(strValue, type);
if (j < dt.Columns.Count - 1)
{
jsonString.Append(strValue + ",");
}
else
{
jsonString.Append(strValue);
}
}
jsonString.Append("},");
}
jsonString.Remove(jsonString.Length - 1, 1);
jsonString.Append("]");
return jsonString.ToString();
}
2.DataTable解析Json数据方法二
/// <summary>
/// dataTable转换成Json格式 【方法二】
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static string DataTable2Json(DataTable dt)
{
StringBuilder jsonBuilder = new StringBuilder();
jsonBuilder.Append("[");
for (int i = 0; i < dt.Rows.Count; i++)
{
jsonBuilder.Append("{");
for (int j = 0; j < dt.Columns.Count; j++)
{
jsonBuilder.Append("\"");
jsonBuilder.Append(dt.Columns[j].ColumnName);
jsonBuilder.Append("\":\"");
jsonBuilder.Append(dt.Rows[i][j].ToString());
jsonBuilder.Append("\",");
}
jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
jsonBuilder.Append("},");
}
if (dt.Rows.Count > 0)
{
jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
}
jsonBuilder.Append("]");
return jsonBuilder.ToString();
}
五、格式化字符型、日期型、布尔型
/// <summary>
/// 格式化字符型、日期型、布尔型
/// </summary>
private static string StringFormat(string str, Type type)
{
if (type == typeof(string))
{
str = String2Json(str);
str = "\"" + str + "\"";
}
else if (type == typeof(DateTime))
{
str = "\"" + str + "\"";
}
else if (type == typeof(bool))
{
str = str.ToLower();
}
else if (type != typeof(string) && string.IsNullOrEmpty(str))
{
str = "\"" + str + "\"";
}
return str;
}