轉:https://blog.csdn.net/dcrmg/article/details/52374194#commentBox
在C#中利用NPOI操作Excel表格非常方便,幾乎上支持所有的Excel表格本身所有的功能,如字體設置、顏色設置、單元格合併、數值計算、頁眉頁腳等等。
這裏準備使用NPOI生成一個班級成績單Excel表格,表格中包含的信息包括學號、姓名、各科成績、平均成績、排名等。
實現原理很簡單,主要是NPOI的一些操作,具體實現的功能包括下邊幾個:
- 單元格合併
- 字體大小、顏色設置
- 背景顏色設置
- 邊框粗細設置
- 多個單元格SUM求和
- 數據寫入和讀取
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NPOI.HSSF.UserModel; using NPOI.XSSF.UserModel; using NPOI.SS.UserModel; using System.IO; using System.Data; namespace Score_Excel { class Program { static void Main(string[] args) { IWorkbook workbook = new HSSFWorkbook();//聲明工作簿對象,可以創建xls或xlsx Excel文件 ISheet sheet1 = workbook.CreateSheet("Score Record"); //創建工作表 ICell sheet1Title = sheet1.CreateRow(0).CreateCell(0); //創建第一行第一個單元格 sheet1Title.SetCellValue("國家體育總局附屬二小幼兒園小一班體育成績表"); //表頭 sheet1Title.CellStyle = GetTitleCellStyle(workbook); sheet1.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 0, 9)); //合併單元格 DataTable dt = GetData(); IRow row; ICell cell; ICellStyle cellStyle1 = GetCellStyle(workbook, 2); ICellStyle cellStyle2 = GetCellStyle(workbook, 0); double[] aveScore = new double[8]; //平均成績數組 int[] rankNum = new int[8]; //名次數組 //表頭數據 row = sheet1.CreateRow(1); cell = row.CreateCell(0); cell.SetCellValue("學號"); cell.CellStyle = cellStyle1; cell = row.CreateCell(1); cell.SetCellValue("姓名"); cell.CellStyle = cellStyle1; cell = row.CreateCell(2); cell.SetCellValue("排球"); cell.CellStyle = cellStyle1; cell = row.CreateCell(3); cell.SetCellValue("乒乓球"); cell.CellStyle = cellStyle1; cell = row.CreateCell(4); cell.SetCellValue("跳水"); cell.CellStyle = cellStyle1; cell = row.CreateCell(5); cell.SetCellValue("舉重"); cell.CellStyle = cellStyle1; cell = row.CreateCell(6); cell.SetCellValue("自由泳"); cell.CellStyle = cellStyle1; cell = row.CreateCell(7); cell.SetCellValue("體操"); cell.CellStyle = cellStyle1; cell = row.CreateCell(8); cell.SetCellValue("平均成績"); cell.CellStyle = cellStyle1; cell = row.CreateCell(9); cell.SetCellValue("名次"); cell.CellStyle = cellStyle1; // 寫入數據 for (int i = 0; i < dt.Rows.Count; i++) { DataRow dataR = dt.Rows[i]; row = sheet1.CreateRow(i + 2); cell = row.CreateCell(0); cell.SetCellValue(dataR["學號"].ToString()); cell.CellStyle = cellStyle2; cell = row.CreateCell(1); cell.SetCellValue(dataR["姓名"].ToString()); cell.CellStyle = cellStyle2; cell = row.CreateCell(2); cell.SetCellValue((Double)dataR["排球"]); cell.CellStyle = cellStyle2; cell = row.CreateCell(3); cell.SetCellValue((Double)dataR["乒乓球"]); cell.CellStyle = cellStyle2; cell = row.CreateCell(4); cell.SetCellValue((Double)dataR["跳水"]); cell.CellStyle = cellStyle2; cell = row.CreateCell(5); cell.SetCellValue((Double)dataR["舉重"]); cell.CellStyle = cellStyle2; cell = row.CreateCell(6); cell.SetCellValue((Double)dataR["自由泳"]); cell.CellStyle = cellStyle2; cell = row.CreateCell(7); cell.SetCellValue((Double)dataR["體操"]); cell.CellStyle = cellStyle2; cell = row.CreateCell(8); cell.SetCellFormula(String.Format("SUM($C{0}:$H{0})/6", i + 3)); cell.CellStyle = cellStyle2; for (int j = 2; j < 8; j++) { aveScore[i] += row.Cells[j].NumericCellValue; } aveScore[i] /= 6; //每個人平均成績 } //以下for循環實現對每個人的成績進行排名 for (int i = 0; i < 8; i++) { rankNum[i] = 1; for (int j = 0; j < 8; j++) { if (aveScore[i] < aveScore[j]) { rankNum[i]++; } } } //排名寫入“名次”列 for (int i = 0; i < 8; i++) { row = sheet1.GetRow(i + 2); cell = row.CreateCell(9); cell.SetCellValue(rankNum[i]); cell.CellStyle = cellStyle2; } if (!Directory.Exists(@"E:\Score Excel")) //檢查是否存在文件夾,不存在則新建 { Directory.CreateDirectory(@"E:\Score Excel"); } FileStream file = new FileStream(@"E:\Score Excel\Score Record.xls", FileMode.Create); workbook.Write(file); file.Close(); workbook.Close(); } static DataTable GetData() //原始數據 { DataTable dt = new DataTable(); dt.Columns.Add("學號", typeof(System.Int32)); dt.Columns.Add("姓名", typeof(System.String)); dt.Columns.Add("排球", typeof(System.Double)); dt.Columns.Add("乒乓球", typeof(System.Double)); dt.Columns.Add("跳水", typeof(System.Double)); dt.Columns.Add("舉重", typeof(System.Double)); dt.Columns.Add("自由泳", typeof(System.Double)); dt.Columns.Add("體操", typeof(System.Double)); dt.Rows.Add("231603001", "張繼科", 100, 83, 69.5, 90, 61, 92); dt.Rows.Add("231603002", "傅園慧", 99, 100, 99.9, 100, 100, 99.5); dt.Rows.Add("231603003", "孫楊", 92, 64, 78.5, 64, 69, 90.5); dt.Rows.Add("231603004", "福原愛", 76, 93.5, 69.5, 85, 87, 61); dt.Rows.Add("231603005", "大魔王", 99, 102, 92, 78, 96.5, 89.5); dt.Rows.Add("231603006", "林丹", 87, 98.5, 78.5, 69.5, 97, 89); dt.Rows.Add("231603007", "丁寧", 85, 93, 87.5, 90.5, 69, 79.5); dt.Rows.Add("231603008", "寧澤濤", 79, 62.5, 87.5, 98, 78, 93.5); return dt; } //設置單元格格式函數,邊框粗細3個可選 static ICellStyle GetCellStyle(IWorkbook workbook, int borderThickness) { ICellStyle cellStyle = workbook.CreateCellStyle(); NPOI.SS.UserModel.BorderStyle borderType; switch (borderThickness) { case 0: borderType = NPOI.SS.UserModel.BorderStyle.Thin; break; case 1: borderType = NPOI.SS.UserModel.BorderStyle.Medium; break; case 2: borderType = NPOI.SS.UserModel.BorderStyle.Thick; break; default: borderType = NPOI.SS.UserModel.BorderStyle.Thin; break; } cellStyle.BorderBottom = borderType; cellStyle.BorderTop = borderType; cellStyle.BorderLeft = borderType; cellStyle.BorderRight = borderType; IFont font = workbook.CreateFont();//設置字體大小和顏色 font.FontName = "宋體"; font.FontHeightInPoints = 13; cellStyle.SetFont(font); return cellStyle; } //設置表頭格式函數 static ICellStyle GetTitleCellStyle(IWorkbook workbook) { ICellStyle cell1Style = workbook.CreateCellStyle(); cell1Style.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center; cell1Style.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center; cell1Style.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin; cell1Style.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin; cell1Style.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin; cell1Style.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin; IFont font = workbook.CreateFont(); //設置字體大小和顏色 font.FontName = "微軟雅黑"; font.FontHeightInPoints = 13; font.Color = NPOI.HSSF.Util.HSSFColor.Blue.Index; cell1Style.SetFont(font); cell1Style.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.LightGreen.Index; cell1Style.FillPattern = FillPattern.SolidForeground; return cell1Style; } } }
執行後,在E盤指定目錄下生成了名字是“Score Excel”的表格:
“名次”列的排名實現:
先聲明瞭一個大小爲8的Int數組,默認值設爲1,依次拿當前的平均成績和其他7個的平均成績對比,有幾個大於當前平均成績的元素,就在當前數組值上加上幾,最後得到的就是每個人的排名,實現如下:
//以下for循環實現對每個人的成績進行排名 for (int i = 0; i < 8; i++) { rankNum[i] = 1; for (int j = 0; j < 8; j++) { if (aveScore[i] < aveScore[j]) { rankNum[i]++; } } }
// NPOI excel 流導出
public void ExportMNewReportExcel(int org_info_id, string user_name, string declare_month, string customer_name, string ufsoft_account) { HSSFWorkbook hssfworkbook = new HSSFWorkbook(); //Excel文件的摘要信息 DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation(); dsi.Company = "blog.csdn.net"; hssfworkbook.DocumentSummaryInformation = dsi; SummaryInformation si = PropertySetFactory.CreateSummaryInformation(); si.Subject = "Export Excel"; hssfworkbook.SummaryInformation = si; //列名 ISheet sheet1 = hssfworkbook.CreateSheet("Sheet1"); IRow row0 = sheet1.CreateRow(0); row0.CreateCell(0).SetCellValue("客戶名稱"); row0.CreateCell(4).SetCellValue("基本稅種"); row0.CreateCell(5).SetCellValue("徵收方式"); row0.CreateCell(11).SetCellValue("稅號"); row0.CreateCell(12).SetCellValue("稅局"); row0.CreateCell(13).SetCellValue("專管員"); row0.CreateCell(14).SetCellValue("業務員"); //list = rep.GetList(org_info_id, "", pageIndex, pageSize, out total,param); // var am = new AmArchStockRepository().GetList().Where(x => x.location_no == user_name).ToList(); // resultList = list.Select(r => new // { // data = r, // flag = am.Where(x => x.customer_info_id == r.customer_info_id).Count() > 0 ? "是" : "否" // }); IQueryable<CmCustomerInfo> queryable = null; var cm_rep = new CmCustomerInfoRepository(); if (!string.IsNullOrEmpty(declare_month)) { queryable = cm_rep.GetList(x => x.org_info_id == org_info_id && x.declare_month == declare_month, includeProperties: "SmUser2"); } if (!string.IsNullOrEmpty(customer_name)) { queryable = queryable.Where(x => x.customer_name.Contains(customer_name)); } if (!string.IsNullOrEmpty(ufsoft_account)) { queryable = queryable.Where(x => x.ufsoft_account.Contains(ufsoft_account)); } var list = queryable.ToList(); var am_list = new AmArchStockRepository().GetList().Where(x => x.location_no == user_name ).ToList(); if (list != null && list.Count > 0) { int index = 0; foreach (var item in list) { index++; IRow excelRow = sheet1.CreateRow(index); excelRow.CreateCell(0).SetCellValue(item.customer_name); string isOrfalse = am_list.Where(x => x.customer_info_id == item.customer_info_id).Count() > 0 ? "是" : "否"; excelRow.CreateCell(1).SetCellValue(isOrfalse); excelRow.CreateCell(2).SetCellValue(item.ufsoft_account); excelRow.CreateCell(3).SetCellValue(item.declarer_machine); excelRow.CreateCell(4).SetCellValue(item.tax_type); excelRow.CreateCell(5).SetCellValue(item.tax_levy_method); excelRow.CreateCell(6).SetCellValue(item.accounting_category); excelRow.CreateCell(7).SetCellValue(item.enterprise_type); excelRow.CreateCell(8).SetCellValue(item.tax_invoice_method); excelRow.CreateCell(9).SetCellValue(item.bank_bill_method); excelRow.CreateCell(10).SetCellValue(item.personnel_agency); excelRow.CreateCell(11).SetCellValue(item.tax_code); excelRow.CreateCell(12).SetCellValue(item.tax_bureau); excelRow.CreateCell(13).SetCellValue(item.tax_contact); excelRow.CreateCell(14).SetCellValue(item.sales_name); } //設置excel單元格的寬度 1*256代表一個字符 sheet1.SetColumnWidth(0, 30 * 256); sheet1.SetColumnWidth(1, 12 * 256); sheet1.SetColumnWidth(2, 13 * 256); sheet1.SetColumnWidth(3, 10 * 256); sheet1.SetColumnWidth(4, 15 * 256); sheet1.SetColumnWidth(5, 10 * 256); sheet1.SetColumnWidth(6, 10 * 256); sheet1.SetColumnWidth(7, 10 * 256); sheet1.SetColumnWidth(8, 20 * 256); sheet1.SetColumnWidth(9, 20 * 256); sheet1.SetColumnWidth(10, 20 * 256); sheet1.SetColumnWidth(11, 20 * 256); sheet1.SetColumnWidth(12, 20 * 256); sheet1.SetColumnWidth(13, 20 * 256); sheet1.SetColumnWidth(14, 20 * 256); MemoryStream ms = new MemoryStream(); hssfworkbook.Write(ms); //asp.net輸出的Excel文件名 //如果文件名是中文的話,需要進行編碼轉換,否則瀏覽器看到的下載文件是亂碼。 string fileName = HttpUtility.UrlEncode(string.Format("{0}_{1}" , "月新報表" , DateTime.Now.ToString("yyyyMMddhhmmss") + ".xls")); HttpContext.Current.Response.Clear(); HttpContext.Current.Response.Buffer = true; HttpContext.Current.Response.ContentType = "application/vnd.ms-excel"; //Response.ContentType = "application/download"; //也可以設置成download HttpContext.Current.Response.Charset = Encoding.UTF8.BodyName; HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", fileName)); HttpContext.Current.Response.ContentEncoding = Encoding.UTF8; HttpContext.Current.Response.BinaryWrite(ms.GetBuffer()); HttpContext.Current.Response.End(); } }