代码收藏

1、生产二维码

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Web;  
using System.Drawing;  
using System.IO;  
using System.Drawing.Imaging;  
using ThoughtWorks.QRCode.Codec;  
using System.Drawing.Drawing2D;  
  
namespace MvcGuestBook.Common  
{  
    public class QrCodeNet  
    {  
        /// <summary>  
        /// 生成二维码图片(中间无图片)  
        /// </summary>  
        /// <param name="data">二维码里面的内容</param>  
        public static string GetQrCodeDe(string data)  
        {  
            QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();  
            qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;  
            qrCodeEncoder.QRCodeScale = 4;  
            qrCodeEncoder.QRCodeVersion = 8;  
            qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;  
            System.Drawing.Image image = qrCodeEncoder.Encode(data);  
            string WebPath = "FlexPaper/QRCodeFile/" + DateTime.Now.ToString("yyyy-MM-dd");  
            string DiskPath = HttpContext.Current.Server.MapPath(WebPath);  
            if (!Directory.Exists(DiskPath))  
            {  
                Directory.CreateDirectory(DiskPath);  
            }  
            string FileName = DateTime.Now.ToString("HHmmss") + ".jpg";  
            string FilePath = DiskPath + "/" + FileName;  
            image.Save(FilePath);//写入图片文件中  
            //HttpContext.Current.Response.Write(WebPath + "/" + FileName);  
            //HttpContext.Current.Response.ContentType = "image/png";  
            return WebPath + "/" + FileName;  
        }  
  
  
        /// <summary>  
        /// 生成二维码图片  
        /// </summary>  
        /// <param name="data">二维码里面的内容</param>  
        public static void GetQrCode(string data)   
        {  
            QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();  
            qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;  
            qrCodeEncoder.QRCodeScale = 4;  
            qrCodeEncoder.QRCodeVersion = 8;  
            qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;  
            System.Drawing.Image image = qrCodeEncoder.Encode(data);  
            //System.IO.MemoryStream MStream = new System.IO.MemoryStream();  
            //image.Save(MStream, System.Drawing.Imaging.ImageFormat.Png);  
            //MStream.Dispose();  
            string WebPath = "FlexPaper/QRCodeFile/" + DateTime.Now.ToString("yyyy-MM-dd");  
            string DiskPath = HttpContext.Current.Server.MapPath(WebPath);  
            if (!Directory.Exists(DiskPath))  
            {  
                Directory.CreateDirectory(DiskPath);  
            }  
            string FileName = DateTime.Now.ToString("HHmmss") + ".jpg";  
            string FilePath = DiskPath + "/" + FileName;  
            Image QRImage = CombinImage(image, HttpContext.Current.Server.MapPath("~/Images/1.png"));//添加二维码中间的Log图片  
            //System.IO.MemoryStream MStream1 = new System.IO.MemoryStream();  
            //QRImage.Save(MStream1, System.Drawing.Imaging.ImageFormat.Png);//写入缓存显示在页面  
            //context.Response.BinaryWrite(MStream1.ToArray());  
            //MStream1.Dispose();  
            QRImage.Save(FilePath);//写入图片文件中  
            HttpContext.Current.Response.Write(WebPath + "/" + FileName);  
            //context.Response.ClearContent();  
            HttpContext.Current.Response.ContentType = "image/png";  
        }  
  
        /// <summary>  
        /// 调用此函数后使此两种图片合并,类似相册,有个背景图,中间贴自己的目标图片    
        /// </summary>  
        /// <param name="imgBack">粘贴的源图片</param>  
        /// <param name="destImg">粘贴的目标图片</param>  
        /// <returns>图片</returns>  
        public static Image CombinImage(Image imgBack, string destImg)  
        {  
            Image img = Image.FromFile(destImg); //照片图片  
            if (img.Height != 65 || img.Width != 65)  
            {  
                img = KiResizeImage(img, 65, 65, 0);  
            }  
  
            Graphics g = Graphics.FromImage(imgBack);  
            g.DrawImage(imgBack, 0, 0, imgBack.Width, imgBack.Height);  
            //g.DrawImage(imgBack, 0, 0, 相框宽, 相框高);  
  
            //g.FillRectangle(System.Drawing.Brushes.White, imgBack.Width / 2 - img.Width / 2 - 1, imgBack.Width / 2 - img.Width / 2 - 1,1,1);//相片四周刷一层黑色边框  
  
            //g.DrawImage(img, 照片与相框的左边距, 照片与相框的上边距, 照片宽, 照片高);  
  
            g.DrawImage(img, imgBack.Width / 2 - img.Width / 2, imgBack.Width / 2 - img.Width / 2, img.Width, img.Height);  
  
            GC.Collect();  
            return imgBack;  
        }  
  
        /// <summary>  
        /// Resize图片        
        /// </summary>  
        /// <param name="bmp">原始Bitmap </param>  
        /// <param name="newW">新的宽度</param>  
        /// <param name="newH">新的高度</param>  
        /// <param name="Mode">保留着,暂时未用</param>  
        /// <returns>处理以后的图片</returns>  
        public static Image KiResizeImage(Image bmp, int newW, int newH, int Mode)  
        {  
            try  
            {  
                Image b = new Bitmap(newW, newH);  
                Graphics g = Graphics.FromImage(b);  
                // 插值算法的质量  
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;  
                g.DrawImage(bmp, new Rectangle(0, 0, newW, newH), new Rectangle(0, 0, bmp.Width, bmp.Height), GraphicsUnit.Pixel);  
                g.Dispose();  
                return b;  
            }  
            catch  
            {  
                return null;  
            }  
  
        }  
  
        public bool IsReusable  
        {  
            get  
            {  
                return false;  
            }  
        }  
  
  
  
    }  
}
2、net  mvc 导入导出Excel总结

public class ExcelController : Controller  
    {  
        //  
        // GET: /Excel/  
        Models.zbwxglEntities myMdl = new Models.zbwxglEntities();  
        /// <summary>  
        /// 第一种方法,利用文件输出流进行读写操作  
        /// </summary>  
        public void outExcel()  
        {  
            DataTable dtData = (DataTable)Session["datatable"];  
            string shtnl = "";  
            shtnl = "<table border='1' cellspacing='1' cellpadding='1'>";  
            shtnl = shtnl + "<thead>";  
            for (int j = 0; j < dtData.Columns.Count; j++)  
            {  
                shtnl = shtnl + "<th>" + j + "</th>";  
            }  
            shtnl = shtnl + "</thead><tbody>";  
            for (int i = 0; i < dtData.Rows.Count; i++)  
            {  
                shtnl = shtnl + "<tr>";  
                for (int j = 0; j < dtData.Columns.Count; j++)  
                {  
                        shtnl = shtnl + "<td>" + dtData.Rows[i][j] + "</td>";  
                }  
                shtnl = shtnl + "</tr>";  
            }  
            shtnl = shtnl + "</tbody></table>";  
            ExportToExcel("application/x-excel", "123.xls", shtnl);  
        }  
        public void ExportToExcel(string FieldType, string FileName, string dt)  
        {  
            System.Web.HttpContext.Current.Response.Charset = "utf-8";  
            System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8).ToString());  
            System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");  
            System.Web.HttpContext.Current.Response.ContentType = FieldType;  
            StringWriter tw = new StringWriter();  
            System.Web.HttpContext.Current.Response.Output.Write(dt);  
            System.Web.HttpContext.Current.Response.Flush();  
            System.Web.HttpContext.Current.Response.End();  
        }  
        /// <summary>  
        /// 第二种方法,利用微软自带插件  
        /// </summary>  
        /// <returns></returns>  
        public ActionResult DownloadFile()  
        {  
            try  
            {  
                DataTable dt = (DataTable)Session["datatable"];  
                string strdate = DateTime.Now.ToString("yyyyMMddhhmmss");  
                string str = Server.HtmlEncode(Request.PhysicalApplicationPath).ToString() + "Content\\DownLoadTest\\" + Session["YongHuID"] + strdate + "Excel.xls";  
                if (System.IO.File.Exists(str))  
                {  
                    //如果存在则删除  
                    System.IO.File.Delete(str);  
                }  
                ConvertHelper myConvertHelper = new ConvertHelper();  
                DataTableToExcel(dt, str);  
                System.Threading.Thread.Sleep(5000);  
                return File(str, "application/vnd.ms-excel", strdate + "Excel.xls");  
            }  
            catch  
            {  
                DataTable dt = new DataTable();  
                List<Dictionary<string, object>> ListReturn = ConvertHelper.DtToList(dt);  
                return Json(ListReturn, JsonRequestBehavior.AllowGet);  
            }  
        }  
        public void DataTableToExcel(DataTable datas, string p)  
        {  
  
            Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();  
            app.SheetsInNewWorkbook = 1;  
            app.Workbooks.Add();  
            Microsoft.Office.Interop.Excel.Worksheet sheet = (Microsoft.Office.Interop.Excel.Worksheet)app.ActiveWorkbook.Worksheets[1];  
  
            for (int i = 0; i < datas.Columns.Count; i++)  
            {  
                sheet.Cells[1, i + 1] = datas.Columns[i].ColumnName;  
            }  
  
            for (int i = 0; i < datas.Rows.Count; i++)  
            {  
                for (int j = 0; j < datas.Columns.Count; j++)  
                {  
                    sheet.Cells[2 + i, j + 1] = datas.Rows[i][j].ToString();  
                }  
            }  
  
            app.Visible = true;  
            System.Threading.Thread.Sleep(500);  
            try  
            {  
                app.ActiveWorkbook.SaveAs(p);  
            }  
            catch { }  
            app.Quit();  
        }  
        /// <summary>  
        /// 第三种方法,利用NPOI插件  
        /// </summary>  
        /// <returns></returns>  
        public FileResult DownLoadExcelJiZuChaXunGenRenXiaoFeiJiLu()  
        {  
            DataTable dt = (DataTable)Session["datatable"];//获取需要导出的datatable数据  
            //创建Excel文件的对象  
            NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();  
            //添加一个sheet  
            NPOI.SS.UserModel.ISheet sheet1 = book.CreateSheet("Sheet1");  
            //给sheet1添加第一行的头部标题  
            NPOI.SS.UserModel.IRow row1 = sheet1.CreateRow(0);  
            //row1.RowStyle.FillBackgroundColor = "";  
            for (int i = 0; i < dt.Columns.Count; i++)  
            {  
                row1.CreateCell(i).SetCellValue(dt.Columns[i].ColumnName);  
            }  
            //将数据逐步写入sheet1各个行  
            for (int i = 0; i < dt.Rows.Count; i++)  
            {  
                NPOI.SS.UserModel.IRow rowtemp = sheet1.CreateRow(i + 1);  
                for (int j = 0; j < dt.Columns.Count; j++)  
                {  
                    rowtemp.CreateCell(j).SetCellValue(dt.Rows[i][j].ToString().Trim());  
                }  
            }  
            string strdate = DateTime.Now.ToString("yyyyMMddhhmmss");//获取当前时间  
            // 写入到客户端   
            System.IO.MemoryStream ms = new System.IO.MemoryStream();  
            book.Write(ms);  
            ms.Seek(0, SeekOrigin.Begin);  
            return File(ms, "application/vnd.ms-excel", strdate + "Excel.xls");  
        }  
        /// <summary>  
        /// Excel导入  
        /// </summary>  
        /// <returns></returns>  
        public ActionResult GetTableFromExcel()  
        {  
            //FileStream file = new FileStream(Server.HtmlEncode(Request.PhysicalApplicationPath).ToString() + "excel\\123.xlsx", FileMode.Open, FileAccess.Read);  
  
            HttpPostedFileBase fostFile = Request.Files["file1"];  
            Stream streamfile = fostFile.InputStream;  
            //HSSFWorkbook hssfworkbook = new HSSFWorkbook(streamfile);  
            HSSFWorkbook hssfworkbook = new HSSFWorkbook(streamfile);  
            using (NPOI.SS.UserModel.ISheet sheet = hssfworkbook.GetSheetAt(0))  
            {  
                DataTable table = new DataTable();  
                IRow headerRow = sheet.GetRow(0);//第一行为标题行  
                int cellCount = headerRow.LastCellNum;//LastCellNum = PhysicalNumberOfCells  
                int rowCount = sheet.LastRowNum;//LastRowNum = PhysicalNumberOfRows - 1  
                //handling header.  
                for (int i = headerRow.FirstCellNum; i < cellCount; i++)  
                {  
                    DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue);  
                    table.Columns.Add(column);  
                }  
                for (int i = (sheet.FirstRowNum + 1); i <= rowCount; i++)  
                {  
                    IRow row = sheet.GetRow(i);  
                    DataRow dataRow = table.NewRow();  
                    if (row != null)  
                    {  
                        for (int j = row.FirstCellNum; j < cellCount; j++)  
                        {  
                            if (row.GetCell(j) != null)  
                                dataRow[j] = GetCellValue(row.GetCell(j));  
                        }  
                    }  
                    table.Rows.Add(dataRow);  
                }  
                for (int i = 0; i < table.Rows.Count; i++)  
                {  
                    //myUpLoadBLL.ForDownLoad(table.Rows[i][1].ToString(), table.Rows[i][2].ToString(),Convert.ToBoolean( table.Rows[i][3]));  
                }  
            }  
            return Content("");  
        }  
        /// <summary>  
        /// 根据Excel列类型获取列的值  
        /// </summary>  
        /// <param name="cell">Excel列</param>  
        /// <returns></returns>  
        private static string GetCellValue(ICell cell)  
        {  
            if (cell == null)  
                return string.Empty;  
            switch (cell.CellType)  
            {  
                case CellType.BLANK:  
                    return string.Empty;  
                case CellType.BOOLEAN:  
                    return cell.BooleanCellValue.ToString();  
                case CellType.ERROR:  
                    return cell.ErrorCellValue.ToString();  
                case CellType.NUMERIC:  
                case CellType.Unknown:  
                default:  
                    return cell.ToString();  
                case CellType.STRING:  
                    return cell.StringCellValue;  
                case CellType.FORMULA:  
                    try  
                    {  
                        HSSFFormulaEvaluator e = new HSSFFormulaEvaluator(cell.Sheet.Workbook);  
                        e.EvaluateInCell(cell);  
                        return cell.ToString();  
                    }  
                    catch  
                    {  
                        return cell.NumericCellValue.ToString();  
                    }  
            }  
        }  
    }  



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值