
代碼:
var execl_path = @"G:\zhyue\backup\項目修改-工作日常\2018-11-12 區域樓盤中心點和放大比例計算\a.xlsx"; Workbook wb = new Workbook(); Worksheet sheet = wb.Worksheets[0]; //添加表頭 sheet.Cells[0, 0].SetCell("區域", Color.FromArgb(196, 248, 170)); sheet.Cells[0, 1].SetCell("商圈", Color.FromArgb(196, 248, 170)); sheet.Cells[0, 2].SetCell("經度", Color.FromArgb(196, 248, 170)); sheet.Cells[0, 3].SetCell("緯度", Color.FromArgb(196, 248, 170)); sheet.Cells[0, 4].SetCell("實際距離", Color.FromArgb(196, 248, 170)); sheet.Cells[0, 5].SetCell("縮放比例", Color.FromArgb(196, 248, 170)); sheet.Cells[0, 6].SetCell("區域最大房源數", Color.FromArgb(196, 248, 170)); sheet.Cells[0, 7].SetCell("區域最小房源數", Color.FromArgb(196, 248, 170)); sheet.Cells[0, 8].SetCell("區域最大最小房源數比", Color.FromArgb(196, 248, 170)); sheet.Cells[0, 9].SetCell("執行級別(1-3)", Color.FromArgb(196, 248, 170)); int row = 1;//第幾行 list_reach.ForEach(s => { int i = 1; GetResult(s.SQID, out longitude, out latitude, out distance, out scale, out max_com_num, out min_com_num, out max_min_scale, ref i); sheet.Cells[row, 0].SetCell(s.C_ReachName, Color.White); sheet.Cells[row, 1].SetCell(s.SQName, Color.White); sheet.Cells[row, 2].SetCell(longitude, Color.White); sheet.Cells[row, 3].SetCell(latitude, Color.White); sheet.Cells[row, 4].SetCell(distance, Color.White); sheet.Cells[row, 5].SetCell(scale, Color.White); sheet.Cells[row, 6].SetCell(max_com_num, Color.White); sheet.Cells[row, 7].SetCell(min_com_num, Color.White); sheet.Cells[row, 8].SetCell(max_min_scale, Color.White); sheet.Cells[row, 9].SetCell(i - 1, Color.White); row++; }); sheet.setColumnWithAuto(); wb.Save(execl_path);
引用擴展類
static class Cells1 { /// <summary> /// 設置cell的Value和Style /// </summary> /// <param name="cell"></param> /// <param name="name"></param> /// <param name="bgColor"></param> public static void SetCell(this Cell cell, object name, Color bgColor) { cell.PutValue(name);//單元格值 Style style = new CellsFactory().CreateStyle(); style.ForegroundColor = bgColor; style.Pattern = BackgroundType.Solid;//背景顏色不起作用,加入該行代碼 style.Borders[BorderType.LeftBorder].LineStyle = CellBorderType.Thin; //應用邊界線 左邊界線 style.Borders[BorderType.RightBorder].LineStyle = CellBorderType.Thin; //應用邊界線 右邊界線 style.Borders[BorderType.TopBorder].LineStyle = CellBorderType.Thin; //應用邊界線 上邊界線 style.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Thin; //應用邊界線 下邊界線 style.HorizontalAlignment = TextAlignmentType.Center; style.VerticalAlignment = TextAlignmentType.Center; cell.SetStyle(style); } /// <summary> /// 設置表頁的列寬度自適應 /// </summary> /// <param name="sheet">worksheet對象</param> public static void setColumnWithAuto(this Worksheet sheet) { Cells cells = sheet.Cells; int columnCount = cells.MaxColumn; //獲取表頁的最大列數 int rowCount = cells.MaxRow; //獲取表頁的最大行數 for (int col = 0; col <= columnCount; col++) { sheet.AutoFitColumn(col, 0, rowCount); } for (int col = 0; col <= columnCount; col++) { cells.SetColumnWidthPixel(col, cells.GetColumnWidthPixel(col) + 30); } } }
