1.添加nuget包管理中的引用 ZXing.Net或QrCode.Net或ThoughtWorks.QRCode
2.前台页面 AssetsListNew.aspx
//监听行工具条
table.on('tool(demo)', function (obj) {
var data = obj.data;
if (obj.event === 'make') {
location.href = "AssetsListNew.aspx?action=make&id=" + data.id + "";
//alert("可以生成" + data.id + "的二维码")
//make(table, obj.data.id);
//layer.msg('ID:' + data.id + ' 的查看操作');
} else if (obj.event === 'del') {
del(table, obj.data.id);
}
else if (obj.event === 'edit') {
location.href = "AssetsListNewAdd.aspx?action=edit&id=" + data.id + "";
//EditData1('auto', "id", "修改", "PAManager/AssetsAdd.aspx?action=edit&id=" + data.id + "", '75%', '80%');
//EditData1('auto', "id", "修改", "../DiBaoGuanLi/60_Add.aspx?idcard=" + data.idcard + "", '75%', '80%');
}
});
3.后台Common工具类CreateORCode.cs
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZXing;
using ZXing.QrCode;
using ZXing.QrCode.Internal;
namespace Common
{
public class CreateORCode
{
public static Bitmap GenerateQrCode(string text, int w, int h, string desc = "")
{
BarcodeWriter writer = new BarcodeWriter();
writer.Format = BarcodeFormat.QR_CODE;
QrCodeEncodingOptions options = new QrCodeEncodingOptions()
{
DisableECI = true,//设置内容编码
CharacterSet = "UTF-8", //设置二维码的宽度和高度
Width = w,
Height = h,
Margin = 1//设置二维码的边距,单位不是固定像素
};
writer.Options = options;
Bitmap map = writer.Write(text);
if (!string.IsNullOrWhiteSpace(desc))
{
return AddText(desc, map, w, h);
}
return map;
}
public static Bitmap GenerateQrCodeWithLogo(string text, int w, int h, string logoUrl, string desc = "")
{
Bitmap logo = new Bitmap(logoUrl);
//构造二维码写码器
MultiFormatWriter writer = new MultiFormatWriter();
Dictionary<EncodeHintType, object> hint = new Dictionary<EncodeHintType, object>();
hint.Add(EncodeHintType.CHARACTER_SET, "UTF-8");
hint.Add(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hint.Add(EncodeHintType.MARGIN, 1);
//生成二维码
var bm = writer.encode(text, BarcodeFormat.QR_CODE, w, h, hint);
BarcodeWriter barcodeWriter = new BarcodeWriter();
Bitmap map = barcodeWriter.Write(bm);
//获取二维码实际尺寸(去掉二维码两边空白后的实际尺寸)
int[] rectangle = bm.getEnclosingRectangle();
//计算插入图片的大小和位置
int middleW = Math.Min((int)(rectangle[2] / 3), logo.Width);
int middleH = Math.Min((int)(rectangle[3] / 3), logo.Height);
int middleL = (map.Width - middleW) / 2;
int middleT = (map.Height - middleH) / 2;
Bitmap bmpimg = new Bitmap(map.Width, map.Height, PixelFormat.Format32bppArgb);
using (Graphics g = Graphics.FromImage(bmpimg))
{
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
g.DrawImage(map, 0, 0, w, h);
//白底将二维码插入图片
g.FillRectangle(Brushes.White, middleL, middleT, middleW, middleH);
g.DrawImage(logo, middleL, middleT, middleW, middleH);
}
if (!string.IsNullOrWhiteSpace(desc))
{
return AddText(desc, map, w, h);
}
return bmpimg;
}
private static Bitmap AddText(string desc, Bitmap qrBitMap, int width, int height)
{
var txtHeight = 30; // 默认一行文字
Font font = new Font("GB2312", 11, FontStyle.Regular);//设置字体,大小
SolidBrush sbrush = new SolidBrush(Color.Black); // 设置颜色
var newMap = new Bitmap(width, height + txtHeight);
Graphics g = Graphics.FromImage(newMap);
g.Clear(Color.White);
var format = StringFormat.GenericDefault;
format.LineAlignment = StringAlignment.Center;
format.Alignment = StringAlignment.Center;
g.DrawString(desc, font, sbrush, new RectangleF(0, height, width, txtHeight), format);
// 合并位图
g.DrawImage(qrBitMap, new Rectangle(0, 0, width, height));
g.Dispose();
return newMap;
}
/// <summary>
/// 解码二维码
/// </summary>
/// <param name="barcodeBitmap">待解码的二维码图片</param>
/// <returns>扫码结果</returns>
public static string DecodeQrCode(Bitmap barcodeBitmap)
{
BarcodeReader reader = new BarcodeReader();
reader.Options.CharacterSet = "UTF-8";
var result = reader.Decode(barcodeBitmap);
return (result == null) ? null : result.Text;
}
}
}
4.前台页面的后台代码调用AssetsListNew.aspx.cs
using Common;
using DAL;
using DQPA.BLL;
using DQPA.IBLL;
using DQPA.MODEL;
using Gma.QrCodeNet.Encoding;
using Gma.QrCodeNet.Encoding.Windows.Render;
using Maticsoft.DBUtility;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace DQPA.PAManager
{
public partial class AssetsListNew : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Auxiliary aux = new Auxiliary();
if (Session["UId"] == null || string.IsNullOrEmpty(Server.UrlDecode(Session["UId"].ToString())))
{
Response.Redirect("UserLogin.aspx");
return;
}
if (!IsPostBack)
{
var action = Request.QueryString["action"];
var id = Request.QueryString["id"];
switch (action)
{
case "list":
loadAssets();
break;
case "delete":
DelAssets();
break;
case "upload":
//var fileup = test8.PostedFile;
//Upload(fileup);
break;
case "make":
MakeORCode(id);
break;
case "down":
DownloadOperation();
break;
default:
break;
}
}
//var a = hidSearch.Value;
//var b = txtCondition.Value;
//var download = Request.QueryString["down"];
//if (download != null)
//{
// var downtype = download.ToString();
// switch (downtype)
// {
// case "1":
// DownloadOperation();
// break;
// default:
// break;
// }
//}
}
protected void loadAssets()
{
try
{
//DataTable dt = new DataTable();
int count;
StringBuilder strwhere = new StringBuilder();
IAssetsBll assetsBll = new AssetsBll();
strwhere.Append(" 1=1");//and ylyid in (select id from M_yanglaoyuan where type ='" + type + "')
strwhere.Append(" and ISNULL(IsDelete,0) <> 1 ");
//if (!string.IsNullOrEmpty(txtCondition.Value))
//{
// where.Append(" and Number like '%" + txtCondition.Value + "%' or type like '%" + txtCondition.Value + "%' or brand like '%" + txtCondition.Value + "%' ");
//}
var searchC = Request.QueryString["selectc"];
var txtsearch = Request.QueryString["txtselect"];
var startTime = Request.QueryString["start"];
var endTime = Request.QueryString["end"];
if (searchC != null && !string.IsNullOrEmpty(searchC))
{
if (txtsearch != null && !string.IsNullOrEmpty(txtsearch))
{
var whereSearch = string.Format(@" and {0} like '%" + txtsearch + "%'", searchC);
strwhere.Append(whereSearch);
}
}
if (!string.IsNullOrEmpty(startTime))
{
if (!string.IsNullOrEmpty(endTime))
{
DateTime start1 = DateTime.ParseExact(startTime, "yyyy-MM-dd", System.Globalization.CultureInfo.CurrentCulture);
//DateTime fStart = start1.AddDays(1);
DateTime fStart = DateTime.ParseExact(endTime, "yyyy-MM-dd", System.Globalization.CultureInfo.CurrentCulture).AddDays(1);
//if (start1 <= fStart)
//{
strwhere.Append(" and PurchaseTime >= '" + start1 + "' and PurchaseTime < '" + fStart + "'");
//}
}
}
//if (!string.IsNullOrEmpty(start.Value))
//{
// if (!string.IsNullOrEmpty(end.Value))
// {
// DateTime start1 = DateTime.ParseExact(start.Value, "yyyy-MM-dd", System.Globalization.CultureInfo.CurrentCulture);
// //DateTime fStart = start1.AddDays(1);
// DateTime fStart = DateTime.ParseExact(end.Value, "yyyy-MM-dd", System.Globalization.CultureInfo.CurrentCulture).AddDays(1);
// strwhere.Append(" and PurchaseTime >= '" + start1 + "' and PurchaseTime < '" + fStart + "'");
// }
//}
//if (hidSearch.Value != null && !string.IsNullOrEmpty(hidSearch.Value))
//{
// if (txtCondition.Value != null && !string.IsNullOrEmpty(txtCondition.Value))
// {
// var whereSearch = string.Format(@" and {0} like '%" + txtCondition.Value + "%'", hidSearch.Value, txtCondition.Value);
// strwhere.Append(whereSearch);
// }
//}
int page = Request.Form["page"] != "" ? Convert.ToInt32(Request.Form["page"]) : 0;
int size = Request.Form["rows"] != "" ? Convert.ToInt32(Request.Form["rows"]) : 0;
string sort = Request.Form["sort"] != "" ? Request.Form["sort"] : "";
string order = Request.Form["order"] != "" ? Request.Form["order"] : "";
var dt = assetsBll.DataPage("Assets", "*,CONVERT(varchar(100), PurchaseTime, 23) as PurchaseTime1", "addtime", "desc", size, page, strwhere.ToString(), out count);
string json = string.Empty;
//if (dt != null && dt.Rows.Count > 0 && dt.Rows[0] != null)
//{
json = JsonHelper.CreateJsonParameters(dt, true, count);
//}
//else
//{
// json = JsonHelper.CreateJsonParameters(null, false, count);
//}
Response.Write(json);
Response.End();
}
catch (Exception ex)
{
throw ex;
}
}
public void DelAssets()
{
var id = Request.QueryString["id"];
if (id != null)
{
string msg = "";
IAssetsBll bll = new AssetsBll();
if (!string.IsNullOrEmpty(id))
{
bool res = bll.DeleteDetail(Convert.ToInt32(id), out msg);
if (res)
{
Response.Write("{\"code\": 0,\"msg\": \"\",\"data\": {\"src\": \"\"}}");
Response.End();
//Response.Write("{\"code\": 0,\"msg\": \"\",\"data\": {\"src\": \"\"}}");
}
else
{
Response.Write("{\"code\": 1,\"msg\": \"\",\"data\": {\"src\": \"\"}}");
Response.End();
}
}
}
else
{
Response.Write("{\"code\": 1,\"msg\": \"\",\"data\": {\"src\": \"\"}}");
Response.End();
}
}
#region 下载上传模板
protected void DownloadOperation()
{
//string filePath = Server.MapPath("../excel") + @"\" + "电脑盘点导入模板.xls" + "";
string filePath = Server.MapPath("../excel") + @"\" + "电脑盘点导入模板.xlsx" + "";
byte[] data = File.ReadAllBytes(filePath);
MemoryStream stream = new MemoryStream(data);
Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", "电脑盘点导入模板.xlsx"));
Response.BinaryWrite(stream.ToArray());
stream.Close();
stream.Dispose();
//File.Delete(filePath);
Response.End();
}
#endregion
#region 导入excel .xlsx
protected void btnImport_Click(object sender, EventArgs e)
{
var fileup = fileUpload.PostedFile;
//InsetData(Upload(fileup));
//InsetData(fileup);
// 说明:导入的方法
if (fileUpload == null)
{
Response.Write("<script>alert('请先选择Excel文件!');window.location.href='AssetsListNew.aspx'</script>");
}
else
{
string fileUrl = "";
#region 文件上传
//try
//{
//}
//catch
//{
// Response.Write("<script>alert('数据上传失败,请重新导入');window.location.href='table.aspx'</script>");
// res = false;
//}
//全名
string excelFile = this.fileUpload.PostedFile.FileName;
//获取文件名(不包括扩展名)
string fileName = Path.GetFileNameWithoutExtension(fileup.FileName);
if (fileName == "" || fileName == null)
{
Response.Write("<script>alert('请先选择Excel文件!');window.location.href='AssetsListNew.aspx'</script>");
}
else
{
//扩展名
string extentionName = excelFile.Substring(excelFile.LastIndexOf(".") + 1);
if (extentionName != "xlsx")
{
Response.Write("<script>alert('您上传的不是.xlsx文件!');window.location.href='AssetsListNew.aspx'</script>");
}
else
{
//浏览器安全性限制 无法直接获取客户端文件的真实路径,将文件上传到服务器端 然后获取文件源路径
#region 设置上传路径将文件保存到服务器
string dateTime = DateTime.Now.Date.ToString("yyyyMMdd");
string time = DateTime.Now.ToShortTimeString().Replace(":", "");
string newFileName = dateTime + time + DateTime.Now.Millisecond.ToString() + ".xlsx";
//自己创建的文件夹 位置随意 合理即可
fileUrl = Server.MapPath("..\\excel") + "\\" + newFileName;
//fileUrl = Path.Combine(Request.MapPath("~/excel"), Path.GetFileName(fileup.FileName));
fileup.SaveAs(fileUrl);
//DataTable dtData = ExcelHelper.Import(fileUrl);
//得到EXCEL的第二种方法(第一个参数是文件流,第二个是excel标签名,第三个是第几行开始读0算第一行)
DataTable dt = ExcelHelper.RenderDataTableFromExcel(fileUrl, "Sheet1", 0);
//Response.Write("<script>alert('已经上传到服务器文件夹')</script>");
//return fileUrl;
//3.删除服务器上的excel文件 获取路径并且删除
//string FilePath = Server.MapPath(fileUrl); // 必须转化以下文件路径,不能直接delete("image/4jpg");
File.Delete(fileUrl);
#endregion
#region dt导入数据库
//3:从System.Data.DataTable导入数据到数据库
//@param System.Data.DataTable dt
IAssetsBll assetBll = new AssetsBll();
IUserBll userBll = new UserBll();
int i = 0;
int num = 1;
string numList = string.Empty;
bool result = false;
var addTime = DateTime.Now;
var updateTime = DateTime.Now;
if (dt != null && dt.Rows.Count > 0 && dt.Rows[0] != null)
{
//查找现在数据表数据
var assetsList = assetBll.SearchList(string.Format(@"select * from assets withnolck"));
string msg = "";
foreach (DataRow dr in dt.Rows)
{
try
{
num += 1;
if (dr != null)
{
Assets assetmodel = new Assets();
if (dr[0] != null)
{
assetmodel.Number = dr[0].ToString().Trim();
if (dr[1] != null)
{
assetmodel.Type = dr[1].ToString().Trim();
}
if (dr[2] != null)
{
assetmodel.Brand = dr[2].ToString().Trim();
}
if (dr[3] != null)
{
assetmodel.IsMac = dr[3].ToString().Trim();
}
if (dr[4] != null)
{
assetmodel.VideoCard = dr[4].ToString().Trim();
}
if (dr[5] != null)
{
assetmodel.RAM = dr[5].ToString().Trim();
}
if (dr[6] != null)
{
assetmodel.RigidDisk = dr[6].ToString().Trim();
}
if (dr[7] != null)
{
assetmodel.CPU = dr[7].ToString().Trim();
}
if (!(dr[8] is DBNull))
{
DateTime purchaseTime = DateTime.Now;
if (DateTime.TryParse(dr[8].ToString(), out purchaseTime))
{
assetmodel.PurchaseTime = Convert.ToDateTime(dr[8].ToString());
}
}
if (!(dr[9] is DBNull))
{
assetmodel.Monetary = Convert.ToDecimal(dr[9]);
}
if (dr[10] != null)
{
assetmodel.Size = dr[10].ToString().Trim();
}
if (dr[11] != null)
{
assetmodel.Department = dr[11].ToString().Trim();
}
if (dr[12] != null)
{
assetmodel.BelongName = dr[12].ToString().Trim();
string sql = string.Format(@"select top 1 id from [user] where account = '{0}'", assetmodel.BelongName);
var dtUser = userBll.SearchAll(sql);
if (dtUser != null && dtUser.Rows.Count > 0 && dtUser.Rows[0] != null)
{
assetmodel.BelongUser = Convert.ToInt32(dtUser.Rows[0]["id"]);
}
}
if (dr[13] != null)
{
assetmodel.Position = dr[13].ToString().Trim();
}
if (dr[14] != null)
{
assetmodel.ProDirection = dr[14].ToString().Trim();
}
if (!(dr[15] is DBNull))
{
assetmodel.SellingPrice = Convert.ToDecimal(dr[15]);
}
if (dr[16] != null)
{
assetmodel.Remark = dr[16].ToString().Trim();
}
assetmodel.AddTime = addTime;
assetmodel.UpdateTime = updateTime;
var assetsId = assetsList.Where(t => t.Number == assetmodel.Number).Select(m => m.Id).FirstOrDefault();
if (assetsId > 0)//存在就修改
{
assetmodel.AddTime = assetsList.Where(t => t.Number == assetmodel.Number).Select(m => m.AddTime).FirstOrDefault();
assetmodel.UpdateTime = updateTime;
assetmodel.Id = assetsId;
result = assetBll.Update(assetmodel, out msg);
}
else//不存在就添加
{
result = assetBll.Add(assetmodel, out msg);
}
}
}
if (result)
{
i++;
}
else
{
numList = numList + num + ',';
continue;
//Response.Write("<script>alert(' 导入失败,数据格式出错!');window.location.href='AssetsList.aspx'</script>");
}
}
catch (Exception ex)
{
numList = numList + num + ',';
//continue;
throw ex;
//Response.Write("<script>alert(' 未完全导入:共导入" + i + "组数据! 未完全导入数据为第" + numList.Trim(',') + "行!');window.location.href='AssetsList.aspx'</script>");
}
}
}
else
{
Response.Write("<script>alert('EXCEL文件为空文件!');window.location.href='AssetsListNew.aspx'</script>");
}
if (numList == string.Empty)
{
Response.Write("<script>alert(' 导入成功:共导入" + i + "组数据!');window.location.href='AssetsListNew.aspx'</script>");
//res = true;
}
else
{
Response.Write("<script>alert(' 未完全导入:共导入" + i + "组数据! 未完全导入数据为第" + numList.Trim(',') + "行!');window.location.href='AssetsListNew.aspx'</script>");
//res = true;
}
}
}
#endregion
#endregion
}
}
#endregion
protected Assets loadAssets(string id)
{
var assets = new Assets();
try
{
IAssetsBll assetsBll = new AssetsBll();
string sql = string.Format(@"select * from Assets withnolock where ISNULL(IsDelete,0)<>1 and id='{0}'", id);
var assetsList = assetsBll.SearchList(sql);
if (assetsList.Any())
{
assets = assetsList.FirstOrDefault();
}
return assets;
}
catch (Exception ex)
{
throw ex;
}
}
protected void MakeORCode(string id)
{
try
{
var asset = loadAssets(id);
if (asset.Id > 0)
{
var url = Server.MapPath("..\\qrcode") + "\\" + "bg.jpg";
//var urlHtml = Server.MapPath("UserLogin.aspx");
string urlHtml = string.Format(@"AssetDetailsShow.aspx?id='{0}'", asset.Id);
var img = CreateORCode.GenerateQrCodeWithLogo(urlHtml, 400, 400, url, "资产编号:" + asset.Number);
System.IO.MemoryStream MStream = new System.IO.MemoryStream();
img.Save(MStream, System.Drawing.Imaging.ImageFormat.Png);
Response.ClearContent();
//Response.ContentType = "image/Png";
//Response.BinaryWrite(MStream.ToArray());
//Response.End();
Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", asset.Number + ".png"));
Response.BinaryWrite(MStream.ToArray());
//string dateTime = DateTime.Now.Date.ToString("yyyyMMdd");
//string time = DateTime.Now.ToShortTimeString().Replace(":", "");
//string newFileName = dateTime + time + DateTime.Now.Millisecond.ToString() + ".png";
//string fileUrl = Server.MapPath("..\\qrcode") + "\\" + newFileName;
string fileUrl = Server.MapPath("..\\qrcode") + "\\" + asset.Number + ".png";
if (System.IO.File.Exists(fileUrl))
{
//存在文件
FileInfo file = new FileInfo(fileUrl);
file.Delete();
}
//不存在文件
FileStream fs = new FileStream(fileUrl, FileMode.CreateNew, FileAccess.ReadWrite);
BinaryWriter bw = new BinaryWriter(fs, UTF8Encoding.UTF8);
byte[] by = MStream.ToArray();
for (int i = 0; i < MStream.ToArray().Length; i++)
{
bw.Write(by[i]);
}
fs.Close();
MStream.Close();
MStream.Dispose();
//Response.End();
//Response.Write("<script>alert('成功生成二维码!');</script>");
}
else
{
Response.Write("<script>window.location.href='AssetsListNew.aspx';alert('生成二维码失败,不存在该条记录!');</script>");
}
}
catch (Exception ex)
{
throw ex;
}
}
}
}