2023/10/05(Thu) 17:00:54 編集(投稿者)
■No102457 (KOZ) に返信
> セルの幅やフォントを設定していろいろ試してみるしかないかと。
> TextRenderer.MeasureText メソッドの値が目安になるかもしれないですが、やってみないとわかりません。
イケたかも。
using ClosedXML.Excel;
using System;
using System.Drawing;
using System.Windows.Forms;
internal class Program
{
static void Main(string[] args) {
const string filename = @"Z:\MergedRowHeight.xlsx";
const string longText = "This is a long text that will be merged across multiple cells.";
using (var workbook = new XLWorkbook()) {
var worksheet = workbook.Worksheets.Add("Sheet1");
var A1 = worksheet.Cell("A1");
A1.Value = longText;
A1.Style.Alignment.SetWrapText(true);
var A2_A3 = worksheet.Range("A2:A3");
A2_A3.Merge();
A2_A3.Value = longText;
A2_A3.Style.Alignment.Vertical = XLAlignmentVerticalValues.Top;
A2_A3.Style.Alignment.SetWrapText(true);
worksheet.Row(2).Height = A2_A3.GetHeight(longText)
- worksheet.Row(3).Height;
workbook.SaveAs(filename);
}
}
}
internal static class ExcelUtl
{
const int DPI = 96;
const double PointsPerInch = 72.0;
const double PixelsPerChar = 7;
public static double GetHeight(this IXLRange range, string text) {
return range.Cell(1, 1).GetHeight(text);
}
public static double GetHeight(this IXLCell cell, string text) {
var font = CreateFont(cell.Style.Font);
var width = (int)(PixelsPerChar * cell.WorksheetColumn().Width);
using (var g = Graphics.FromHwnd(IntPtr.Zero)) {
var size = new Size(width, short.MaxValue);
TextFormatFlags flags =
TextFormatFlags.Left | TextFormatFlags.Top | TextFormatFlags.WordBreak;
size = TextRenderer.MeasureText(g, text, font, size, flags);
return PixelsToPoints(size.Height);
}
}
public static int PointsToPixels(double points) {
return (int)(points * DPI / PointsPerInch);
}
public static double PixelsToPoints(int pixels) {
return (int)(pixels * PointsPerInch / DPI);
}
public static Font CreateFont(IXLFont font) {
FontStyle style = FontStyle.Regular;
if (font.Bold) { style |= FontStyle.Bold; }
if (font.Italic) { style |= FontStyle.Italic; }
if (font.Underline != XLFontUnderlineValues.None) { style |= FontStyle.Underline; }
if (font.Strikethrough) { style |= FontStyle.Strikeout; }
return new Font(font.FontName,
(float)font.FontSize, style, GraphicsUnit.Point);
}
}
まぁ試してみてダメだったら調整してください。