我有一个在excel中写数据的方法,但是有些部分包含很多文本,并且该方法将文本包装到列中,但是我无法在行中这样做,因为它们被合并了。所以我得到这样的东西:
我需要像这样:
有没有办法通过代码做到这一点?使用互操作对象。感谢您的帮助。
答案 0 :(得分:2)
我不知道这是否正确,但是我提出了以下解决方案。这个想法如下:
如您所见,此方法是通用的-即,它将对合并区域中的任何行计数起作用,并且将根据新高度遵循每行的先前比率。您可以使用代码下载sample workbook。
VBA
Sub Test()
Call AutoFitMergedCells(Range("D11"))
End Sub
Sub AutoFitMergedCells(cell As Range)
Dim dOldHeight#, dNewHeight#, dPercent#, arow, addr, rows_count
Dim dicCells As New Dictionary, dicHeights As New Dictionary
'// turn off flickering
Application.ScreenUpdating = False
With cell
'// remember rows count for merging cells back
rows_count = .MergeArea.Count
'// every dictionary entry holds following info:
'// 1) original height of all rows in merged cells
'// 2) percentage of row's height to height of all rows in merged area
For Each arow In .MergeArea.Rows
With arow.Cells(1)
Set dicHeights = New Dictionary
dicHeights("height") = .RowHeight
dicHeights("percent") = 0
dicCells.Add Key:=.Address(0, 0), Item:=dicHeights
End With
Next
'// total height of all rows
For Each addr In dicCells.Keys()
dOldHeight = dOldHeight + dicCells(addr)("height")
Next
'// update the percentage of every row
For Each addr In dicCells.Keys()
dicCells(addr)("percent") = dicCells(addr)("height") / dOldHeight
Next
.UnMerge
.EntireRow.AutoFit
'// remember new height
dNewHeight = .RowHeight
'// this applies percentage of previous row's height to new height
For Each addr In dicCells.Keys()
Range(addr).EntireRow.RowHeight = dicCells(addr)("percent") * dNewHeight
Next
'// merge back
.Resize(rows_count).Merge
End With
Application.ScreenUpdating = True
End Sub
C#
using System.Diagnostics;
using Excel = Microsoft.Office.Interop.Excel;
private void ProcessMergedCells()
{
var xlApp = new Excel.Application { Visible = false, ScreenUpdating = false };
// get Excel process in order to kill it after the work is done
var xlHandle = new IntPtr(xlApp.Hwnd);
var xlProc = Process
.GetProcesses()
.First(p => p.MainWindowHandle == xlHandle);
var book = xlApp.Workbooks.Open(@"C:\AutoFitMergedCells.xlsm");
var sheet = book.Sheets[1] as Excel.Worksheet;
// obtain merged cells any way you like
// here I just populate array with arbitrary cells
var merged_ranges = new Excel.Range[]
{
sheet.Range["D11"],
sheet.Range["D13"]
};
// process merged cells
foreach(var merged_range in merged_ranges)
{
AutoFitMergedCells(merged_range);
}
// quit with saving
book.Close(SaveChanges: true);
xlApp.Quit();
// clean up
GC.Collect();
GC.WaitForFullGCComplete();
// kill Excel for sure
xlProc.Kill();
}
private void AutoFitMergedCells(Excel.Range merged_range)
{
double dOldHeight = 0d, dNewHeight = 0d;
var dicCells = new Dictionary<string, Dictionary<string, double>>();
// remember rows count for merging cells back
int rows_count = merged_range.MergeArea.Count;
// every dictionary entry holds following info:
// 1) original height of all rows in merged cells
// 2) percentage of row's height to height of all rows in merged area
foreach (Excel.Range the_row in merged_range.MergeArea.Rows)
{
// we need only top-left cell
var first_cell = the_row.Cells[1];
var dicHeights = new Dictionary<string, double>
{
["height"] = first_cell.RowHeight,
["percent"] = 0d
};
dicCells[first_cell.Address[0, 0]] = dicHeights;
}
// total height of all rows
foreach (string addr in dicCells.Keys)
dOldHeight += dicCells[addr]["height"];
// update the percentage of every row
foreach (string addr in dicCells.Keys)
dicCells[addr]["percent"] = dicCells[addr]["height"] / dOldHeight;
// unmerge range and autofit
merged_range.UnMerge();
merged_range.EntireRow.AutoFit();
// remember new height
dNewHeight = merged_range.RowHeight;
// this applies percentage of previous row's height to new height
var sheet = merged_range.Parent;
foreach (string addr in dicCells.Keys)
sheet.Range[addr].EntireRow.RowHeight = dicCells[addr]["percent"] * dNewHeight;
// merge back
merged_range.Resize[rows_count].Merge();
}
答案 1 :(得分:0)
我不记得我在哪里看到过这个东西,但是我曾经见过一个黑客可以做到这一点。简而言之,您可以从合并的单元格中获取有问题的文本,将其粘贴到同一列中的非合并单元格中,然后对该单元格进行自动拟合以查看其高度。然后,将安全单元的高度设为该高度,然后将其手动设置为每个合并的行,再除以合并的总行数。
这很丑陋,但确实有效。在您的示例中,如果始终为两行,则这将变得非常容易,因为您始终可以将其除以2,并将行数增加2。如果不是,则只需要考虑这一点即可。假设C1是我们的“安全单元”,它将看起来像这样:
Excel.Range testCell = ws.Cells[1, 3];
testCell.WrapText = true;
for (int row = 11; row < ws.UsedRange.Rows.Count; row += 2)
{
testCell.Value2 = ws.Cells[row, 4].Value2;
testCell.Rows.AutoFit();
ws.Range[string.Format("{0}:{1}", row, row + 1)].RowHeight = testCell.RowHeight / 2;
}