Esempio n. 1
0
        /// <summary>
        /// 填充内容
        /// </summary>
        /// <param name="sheet"></param>
        /// <param name="request">待插入数据</param>
        public static void InsertSheetContent(this SheetBuilder sheet, ExcelExportRequest request)
        {
            var titleStyle = GetDefaultStyle(true);
            var rowStyle   = GetDefaultStyle();

            sheet.SetSheetMerges(request.Merges);
            int rowIndex  = request.RowIndex;
            var colWidths = new List <double>();

            foreach (var row in request.RowsData)
            {
                List <double> textRowNums = new List <double>();
                for (int col = 0; col < row.Count; col++)
                {
                    sheet.Worksheet.Cells[rowIndex, col].SetStyle(rowIndex < request.TitleRowCount ? titleStyle : rowStyle);
                    sheet.WriteText(rowIndex, col, row[col] == null ? "" : row[col].Replace("^^", "\n"));
                    int    length = Encoding.UTF8.GetBytes(row[col] == null ? "" : row[col]).Length;
                    double width  = length * 2 < 8 ? 8 : length * 2;
                    if (rowIndex == (request.TitleRowCount - 1))
                    {
                        double colSetWidth = request.ColumnsWidth != null && request.ColumnsWidth.Count > col ? request.ColumnsWidth[col] : 0;
                        double colWidth    = colSetWidth > 0 ? colSetWidth : width;
                        sheet.SetColumnWidth(col, colWidth);
                        colWidths.Add(colWidth);
                    }
                    double textRowNum = 2;
                    if (rowIndex > (request.TitleRowCount - 1) && colWidths.Count > 0)
                    {
                        textRowNum = Math.Ceiling(width / colWidths[col]);
                    }
                    textRowNums.Add(textRowNum);
                }
                var rowHeight = rowStyle.Font.Size * (textRowNums.Max() <= 2 ? 2 : textRowNums.Max());
                sheet.SetRowHeight(rowIndex, rowHeight > 400 ? 400 : rowHeight);
                rowIndex++;
            }
            if (request.IsAutoRowFit)
            {
                sheet.Worksheet.AutoFitRows();
            }
        }