2017-01-13 527 views
2

我正在使用EPPlus和C#並嘗試自動調整/自動調整行的高度以適應用文本換行顯示合併單元格的所有內容所需的高度。然而,不管我嘗試的文本總是截斷。由於我在各種工作表上用各種文本大小重複此過程,因此我不想對行高進行硬編碼(除了對行執行最小高度)。如果可能的話,我想在EPPlus/C#中執行此操作。EPPlus中自動調整合並單元格的行高度

隨着單元格A2:E2合併和WrapText =真:

細胞與文本被截斷

enter image description here

下面是它應該是什麼樣子與所需的單元格高度

enter image description here

這裏是我的相關性和短的C#代碼

Int32 intToCol; 
intToCol = 5; 
eppWorksheet.Cells[2, 1, 2, intToCol].Merge = true; 
eppWorksheet.Cells[2, 1].Style.WrapText = true; 
//Check if at the minimum height. If not, resize the row 
if (eppWorksheet.Row(2).Height < 35.25) 
{ 
    eppWorksheet.Row(2).Height = 35.25; 
} 

我已經看了Autofit rows in EPPlus,它似乎並沒有直接回答我的問題,除非我讀錯了。

+1

這是Excel中的一個記錄的限制:https://support.microsoft.com/en-us/kb/212010。沒有簡單的解決方案恐怕其他然後gusimating的高度,這裏是一個關於寬度自動調整但同樣的主體的帖子:http://stackoverflow.com/questions/18894671/epplus-autofitcolumns-method-fails-when-a-column- has-merged-cells/23528323 – Ernie

+0

我意識到Excel的侷限性,但沒有看到網上的解決方案很適合,並且好奇別人是否有任何解決方案。 – cmbarnett87

回答

7

以下是可重用方法的解決方案。傳遞文本值,用於單元格的字體,合併的列的寬度和接收行高度。用結果設置行高。

使用方法

eppWorksheet.Row(2).Height = MeasureTextHeight(cell.Value, cell.Style.Font, [enter the SUM of column widths A-E]); 

可重複使用的方法

public double MeasureTextHeight(string text, ExcelFont font, int width) 
    { 
     if (string.IsNullOrEmpty(text)) return 0.0; 
     var bitmap = new Bitmap(1, 1); 
     var graphics = Graphics.FromImage(bitmap); 

     var pixelWidth = Convert.ToInt32(width * 7.5); //7.5 pixels per excel column width 
     var drawingFont = new Font(font.Name, font.Size); 
     var size = graphics.MeasureString(text, drawingFont, pixelWidth); 

     //72 DPI and 96 points per inch. Excel height in points with max of 409 per Excel requirements. 
     return Math.Min(Convert.ToDouble(size.Height) * 72/96, 409); 
    } 
+1

非常好的解決方案。請注意,您需要處理'Bitmap'和'Graphics'對象。 – Dylan

+1

如果它不是我的低於15的聲望,我會爲它投票... – cmbarnett87

+0

偉大的解決方案。它在錫上說了什麼。隊友的歡呼聲。 –