1. 程式人生 > 其它 >BarcodeLib.Barcode.dll+NPOI 下載和生成條形碼匯出excel

BarcodeLib.Barcode.dll+NPOI 下載和生成條形碼匯出excel

前端列表展示資料,顯示圖片:

        private void GetList()
        {
            int currPage = Utils.ReqIntParams("page", 1);
            int pageSize = Utils.ReqIntParams("rows", 30);
            int totalCount = 0;
            int totalPage = 0;
            string beginTime = Utils.ReqStrParams("bt", "");
            
string endTime = Utils.ReqStrParams("et", ""); string keyword = Utils.ReqStrParams("keyword", "-1"); int provider = Utils.ReqIntParams("provider", -1); int totalSalesNum = 0; decimal totalSalesMoney = 0; DataTable dt = OrderDB.GetList(keyword, provider, beginTime, endTime,1
, currPage, pageSize, ref totalCount, ref totalPage,ref totalSalesNum, ref totalSalesMoney); DataTable newDT = new DataTable(); newDT.Columns.Add("rowno"); newDT.Columns.Add("PNo"); newDT.Columns.Add("PName"); newDT.Columns.Add(
"BarCode"); newDT.Columns.Add("Proceeds"); newDT.Columns.Add("Refund"); newDT.Columns.Add("totalSalesNum"); newDT.Columns.Add("totalSalesMoney"); for (int i = 0; i < dt.Rows.Count; i++) { DataRow dr = newDT.NewRow(); dr["rowno"] = dt.Rows[i]["rowno"]; dr["PNo"] = dt.Rows[i]["PNo"]; dr["PName"] = dt.Rows[i]["PName"]; dr["BarCode"] = dt.Rows[i]["BarCode"].ToString() != "" ? GenerateBarCodeBySpire(dt.Rows[i]["BarCode"].ToString()) : ""; dr["Proceeds"] = dt.Rows[i]["Proceeds"]; dr["Refund"] = dt.Rows[i]["Refund"]; dr["totalSalesNum"] = dt.Rows[i]["totalSalesNum"]; dr["totalSalesMoney"] = dt.Rows[i]["totalSalesMoney"]; newDT.Rows.Add(dr); } System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.Append("{"); sb.Append("\"total\":"); sb.Append("\"" + totalCount + "\","); sb.Append("\"totalSalesNum\":"); sb.Append("\"" + totalSalesNum + "\","); sb.Append("\"totalSalesMoney\":"); sb.Append("\"" + totalSalesMoney + "\","); newDT.TableName = "rows"; string strjson = XpShopJson.DtToJSON(newDT); if (strjson.Trim() != "") { strjson = strjson.Remove(0, 1); strjson = strjson.Remove(strjson.Length - 1, 1); } sb.Append(strjson); sb.Append("}"); Response.Write(sb.ToString()); } /// <summary> /// 將條形編碼轉成Base64的圖片路徑 /// </summary> /// <param name="codestr"></param> /// <returns></returns> private string GenerateBarCodeBySpire(string codestr) { BarcodeLib.Barcode.Linear barcode = new BarcodeLib.Barcode.Linear(); barcode.Type = BarcodeType.CODE39; barcode.Data = codestr; barcode.UOM = UnitOfMeasure.PIXEL; barcode.BarWidth = 1; barcode.BarHeight = 80; barcode.LeftMargin = 5; barcode.RightMargin = 5; barcode.TopMargin = 5; barcode.BottomMargin = 5; barcode.ImageFormat = System.Drawing.Imaging.ImageFormat.Png; //Bitmap barcodeInBitmap = barcode.drawBarcode(); MemoryStream ms = new MemoryStream(); barcode.drawBarcode(ms); byte[] arr = new byte[ms.Length]; ms.Position = 0; ms.Read(arr, 0, (int)ms.Length); ms.Close(); string pic = Convert.ToBase64String(arr); return pic; }

匯出excel

  1 private void ExportAll() {
  2             int currPage = Utils.ReqIntParams("page", 1);
  3             int pageSize = Utils.ReqIntParams("rows", 9999);
  4             int totalCount = 0;
  5             int totalPage = 0;
  6             string beginTime = Utils.ReqStrParams("bt", "");
  7             string endTime = Utils.ReqStrParams("et", "");
  8             string keyword = Utils.ReqStrParams("keyword", "-1");
  9             int provider = Utils.ReqIntParams("provider", -1);
 10             int totalSalesNum = 0;
 11             decimal totalSalesMoney = 0;
 12             DataTable dt = OrderDB.GetSalesStatistics(keyword, provider, beginTime, endTime, 2,currPage, pageSize, ref totalCount, ref totalPage, ref totalSalesNum, ref totalSalesMoney);
 13             string fileName = "銷售統計資料-" + DateTime.Now.ToString("yyyyMMddHHmmss");
 14             if (dt.Rows.Count > 0)
 15             {
 16                 CreateXls(dt, totalSalesNum,totalSalesMoney,fileName);
 17             }
 18             else {
 19                 Utils.ShowMsg2(this, "沒有可匯出的資料!");
 20             }
 21         }
 22 
 23 public void CreateXls(DataTable dt,int totalSalesNum,decimal totalSalesMoney, string FileName)
 24         {
 25             string sheetName = "銷售統計資料";
 26             //生成的表格的表頭的主體
 27             List<string> liHeadSubject = new List<string>();
 28             liHeadSubject.Add("序號");
 29             liHeadSubject.Add("商品編號");
 30             liHeadSubject.Add("商品名稱");
 31             liHeadSubject.Add("商品條碼");
 32             liHeadSubject.Add("銷售數量");
 33             liHeadSubject.Add("收款金額");
 34             liHeadSubject.Add("退款金額");            
 35             liHeadSubject.Add("銷售金額");
 36             CreateXlsBT(dt,totalSalesNum,  totalSalesMoney, sheetName, liHeadSubject, Context, FileName);
 37         }
 38         
 39         /// <summary>
 40         /// 根據datatable資料內容,生成電子表格,這個是沒有明細的
 41         /// </summary>
 42         /// <param name="dtContent">要匯出的內容</param>
 43         /// <param name="sheetName"> 工作簿的名稱</param>
 44         /// <param name="liHeadSubject">生成的表格的表頭的主體,例如這個訂單的主要資料,訂單總價 收貨人,收貨地,手機,總購買數等</param>
 45         /// <param name="context"></param>
 46         /// <param name="fileName">生成的檔名</param>
 47         public  void CreateXlsBT(DataTable dtContent, int totalSalesNum, decimal totalSalesMoney, string sheetName, List<string> liHeadSubject, HttpContext context, string fileName)
 48         {
 49             //每個工作簿顯示的資料行數//Excel2003版最大行數是65535行
 50             int sheetSize = 65535;
 51             //工作簿個數
 52             double sheetCount = Math.Ceiling(dtContent.Rows.Count * 1.00 / sheetSize);
 53 
 54             XSSFWorkbook book = new XSSFWorkbook();
 55             //建立工作簿
 56             ISheet se = book.CreateSheet(sheetName);
 57             //設定單元格高度
 58            // se.DefaultRowHeight = 35 * 38; //18 * 20;
 59             //建立行
 60             IRow row1 = se.CreateRow(0);
 61 
 62             ;
 63             ICell i0 = row1.CreateCell(0, CellType.String);
 64             i0.SetCellValue("");
 65             ICell i01 = row1.CreateCell(1, CellType.String);
 66             i01.SetCellValue("");
 67             ICell i02 = row1.CreateCell(2, CellType.String);
 68             i02.SetCellValue("");
 69             ICell i03 = row1.CreateCell(3, CellType.String);
 70             i03.SetCellValue("");
 71             ICell i04 = row1.CreateCell(4, CellType.String);
 72             i04.SetCellValue("銷售總數量:" + totalSalesNum);
 73             ICell i05 = row1.CreateCell(5, CellType.String);
 74             i05.SetCellValue("");
 75             ICell i1 = row1.CreateCell(6, CellType.String);
 76             i1.SetCellValue("");
 77             ICell i2 = row1.CreateCell(7, CellType.String);
 78             i2.SetCellValue("銷售總金額:"+totalSalesMoney.ToString());
 79 
 80             //4.建立CellStyle與DataFormat並載入格式樣式
 81             IDataFormat dataformat = book.CreateDataFormat();
 82             ICellStyle style1 = book.CreateCellStyle();
 83             style1.DataFormat = dataformat.GetFormat("0.00");
 84             //建立行
 85             IRow row = se.CreateRow(1);
 86 
 87             //合併表頭列
 88             List<string> liHead = new List<string>(liHeadSubject);
 89             int count = liHead.Count;
 90             for (int i = 0; i < count; i++)//建立表頭
 91             {
 92                 //建立單元格
 93                 ICell ic = row.CreateCell(i, CellType.String);
 94                 ic.SetCellValue(liHead[i].Trim());
 95             }
 96             IRow onerow = se.GetRow(0);
 97             se.GetRow(1).Height= 22 * 24;
 98             onerow.Height = 22 * 24;
 99             int fillEmptyToColumnNum = liHeadSubject.Count;
100             for (int i = 0; i < dtContent.Rows.Count; i++)//建立內容
101             {
102                 row = se.CreateRow(i + 2);
103                 row.Height = 35 * 38;
104                 int columnsCount = dtContent.Columns.Count;
105                 for (int j = 0; j < columnsCount; j++)
106                 {
107                     ICell ic = row.CreateCell(j, CellType.String);
108 
109 
110                     if (j == 3)
111                     {//"data:image/png;base64," + dtContent.Rows[i][j].ToString().Trim()
112                         if (dtContent.Rows[i][j].ToString().Trim() != "")
113                         {
114                             //像excel插入影象
115                             AddCellPicture(se, book, GenerateBarCodeBySpireBitmap(dtContent.Rows[i][j].ToString()), i - 2, j);
116                         }
117 
118                     }
119                     else if (j == 4)
120                     {
121                         ic.SetCellValue((int)dtContent.Rows[i][j]);
122 
123                     } else if (j==7||j==6|| j == 5) {
124                         //ic.CellStyle = style1;
125                         ic.SetCellValue(double.Parse(dtContent.Rows[i][j].ToString().Trim()));
126                     }
127                     else {
128                         ic.SetCellValue(dtContent.Rows[i][j].ToString().Trim());
129 
130                     }
131                 }
132             }
133             se.SetColumnWidth(4, 20 * 256);
134             se.SetColumnWidth(5, 20 * 256);
135             se.SetColumnWidth(6, 20 * 256);
136             se.SetColumnWidth(7, 20 * 256);
137             //寬度自適應
138             for (int columnNum = 0; columnNum < count; columnNum++)
139             {
140                 int columnWidth = se.GetColumnWidth(columnNum) / 256;//獲取當前列寬度  
141                 for (int rowNum = 1; rowNum <= se.LastRowNum; rowNum++)//在這一列上迴圈行  
142                 {
143                     IRow currentRow = se.GetRow(rowNum);
144                     ICell currentCell = currentRow.GetCell(columnNum);
145                     //int length = Encoding.UTF8.GetBytes(currentCell.ToString().Trim()).Length;//獲取當前單元格的內容寬度  
146                     int length = currentCell.ToString().Length;//獲取當前單元格的內容寬度
147                     if (columnWidth < length + 1)
148                     {
149                         columnWidth = length + 1;
150                     }//若當前單元格內容寬度大於列寬,則調整列寬為當前單元格寬度,後面的+1是我人為的將寬度增加一個字元  
151                     
152                 }
153                 if (columnNum==3)
154                 {
155                     se.SetColumnWidth(columnNum, 16 * 840);
156                 }
157                 else { 
158                     se.SetColumnWidth(columnNum, columnWidth * 256);
159                 }
160             }
161 
162 
163             context.Response.AppendHeader("Content-Disposition", "Attachment; FileName=" + fileName + ".xls;");
164             context.Response.ContentType = "application/vnd.ms-excel";
165             context.Response.ContentEncoding = System.Text.Encoding.UTF8;
166             book.Write(context.Response.OutputStream);
167             book.Close();
168             book = null;
169         }
170 
171 
172 /// <summary>
173         /// 將編碼轉成圖形流
174         /// </summary>
175         /// <param name="codestr"></param>
176         /// <returns></returns>
177         private Bitmap GenerateBarCodeBySpireBitmap(string codestr)
178         {
179 
180             BarcodeLib.Barcode.Linear barcode = new BarcodeLib.Barcode.Linear();
181 
182             barcode.Type = BarcodeType.CODE39;
183 
184             barcode.Data = codestr;
185 
186             barcode.UOM = UnitOfMeasure.PIXEL;
187             barcode.BarWidth = 1;
188             barcode.BarHeight = 80;
189             barcode.LeftMargin = 5;
190             barcode.RightMargin = 5;
191             barcode.TopMargin = 5;
192             barcode.BottomMargin = 5;
193 
194             barcode.ImageFormat = System.Drawing.Imaging.ImageFormat.Png;
195             Bitmap barcodeInBitmap = barcode.drawBarcode();
196             return barcodeInBitmap;
197         }
198 
199 
200         /// <summary>
201         /// 向sheet插入圖片
202         /// </summary> 
203         private static void AddCellPicture(ISheet sheet, XSSFWorkbook workbook, Bitmap b, int row, int col)
204         {
205             
206                 Bitmap bitmap = b; //讀取圖片流 
207                 Bitmap OldImage = new Bitmap(bitmap);//將圖片流複製到新的圖片流中 
208                 bitmap.Dispose();   //將原來的圖片流釋放,將圖片檔案進行解鎖。 
209 
210                 using (MemoryStream ms = new MemoryStream())
211                 {
212                     OldImage.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
213                     byte[] bytes = ms.ToArray();
214                    
215                     int pictureIdx = workbook.AddPicture(bytes, NPOI.SS.UserModel.PictureType.JPEG);  //新增圖片 
216                     XSSFDrawing patriarch = (XSSFDrawing)sheet.CreateDrawingPatriarch();
217                     // XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, col, row + 2, col + 1, row + 3);
218                     XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, col, row+4 , col + 1, row + 5);
219                     //圖片位置,圖片左上角為(col, row) 
220                     XSSFPicture pict = (XSSFPicture)patriarch.CreatePicture(anchor, pictureIdx);
221                       //pict.Resize(); //用圖片原始大小來顯示   
222                     /*
223                     int widthPx = 300;
224                     int heightPx = 120;
225                     //設定列寬度,根據公式:POI中的列寬 ≈ 畫素/8*256
226                     decimal width = Math.Round((decimal)(heightPx) / 8, 2);
227                     //將圖片縮小為原來的十分之九
228                     decimal lessWidth = Math.Round(width * 9 / 10, 2);
229                     sheet.SetColumnWidth(col, Decimal.ToInt32(lessWidth * 256));
230                     IRow row3 = sheet.GetRow(row);
231                     //設定行高度,根據公式:POI中的行高 = 畫素/DPI*72*20
232                     decimal poiHeight = Math.Round((decimal)(widthPx) / 7, 2);
233                     //將圖片縮小為原來的十分之九
234                     decimal lessPoiHeight = Math.Round(poiHeight * 9 / 10, 2);
235                     row3.Height = (short)Decimal.ToInt32(lessPoiHeight * 72 * 20);
236                 */
237             }
238 
239         }
各自努力