Apache poi excel ширина столбца
Мне нужно сгенерировать файл MS Excel 2007+ из моего приложения в соответствии с заданным шаблоном, предоставленным руководством. Большая часть работы сделана, но мне нужно установить ширину столбца 11,34 сантиметра. Я пытался использовать setColumnWidth(int columnIndex, int width) метод, но независимо от того, какое значение я предоставил, он не работает. JavaDoc говорит:
Установите ширину (в единицах 1/256 ширины символа)
Максимальная ширина столбца для отдельной ячейки составляет 255 символов. Это значение представляет количество символов, которые могут отображаться в ячейке, отформатированной стандартным шрифтом.
Как это сделать?
задан 01 июн '11, 10:06
Вы проверяли, не настраивается ли автоматическое изменение размера столбца? Убедитесь, что вы не выполняете этот вызов в своем коде, sheet.autoSizeColumn(columnIndex); - maple_shaft
Привет, я не нашел в своем коде похожих вызовов. Мне интересно, есть ли способ вместо этого преобразовать сантиметры в «ширину символа»? Или это вообще не имеет смысла? - gtludwig
2 ответы
Хорошо, я думаю, что теперь я понимаю вашу проблему, ваши бизнес-требования гласят, что вы должны установить ширину столбца на основе стандартной ширины символа шрифта Excel.
Я бы подошел к этому, используя клавишу Print Screen в примере в Excel, затем вставьте в Paint или аналогичную программу и подсчитайте ширину в пикселях. Затем я бы использовал линейку для измерения пикселей / см и использовал полученное число в качестве фиксированной ширины столбца.
Это, вероятно, потребует немного проб и ошибок, чтобы разобраться.
Сказав это, я поделюсь своим личным мнением, что считаю это ЛЕНИВЫМ и СЛАБЫМ бизнес-требованием. Что такое «стандартный шрифт»? Какая версия Excel? Это требование открыто для слишком широкой интерпретации разработчика.
Собственно, я ошибся с самого начала! Моя (ужасная!) Плохая! Ширину столбцов уже задавали, но не подумал! Для этого потребовалось простое «правило трех», и я был настроен.
Sheets are the central structures within a workbook, and are where a user does most of his spreadsheet work. The most common type of sheet is the worksheet, which is represented as a grid of cells. Worksheet cells can contain text, numbers, dates, and formulas. Cells can also be formatted.
Field Summary
Method Summary
Modifier and Type | Method and Description |
---|---|
int | addMergedRegion (CellRangeAddress region) |
Returns the CellStyle that applies to the given (0 based) column, or null if no style has been set for that column
Get the default column width for the sheet (if the columns do not define their own width) in characters
Get the default row height for the sheet (if the rows do not define their own height) in twips (1/20 of a point)
Gets the last row on the sheet Note: rows which had content before and were set to empty later might still be counted as rows by Excel and Apache POI, so the result of this method will include such rows and thus the returned value might be higher than expected!
Flag indicating whether summary columns appear to the right of detail in an outline, when applying an outline.
Gets the flag indicating whether this sheet displays the lines between rows and columns to make editing and reading easier.
Set the default column width for the sheet (if the columns do not define their own width) in characters
Set the default row height for the sheet (if the rows do not define their own height) in twips (1/20 of a point)
Control if Excel should be asked to recalculate all formulas on this sheet when the workbook is opened.
Sets the flag indicating whether this sheet should print the lines between rows and columns to make editing and reading easier.
Sets a page break at the indicated row Breaks occur above the specified row and left of the specified column inclusive.
Flag indicating whether summary columns appear to the right of detail in an outline, when applying an outline.
Verify that merged regions do not intersect multi-cell array formulas and no merged regions intersect another merged region in this sheet.
Methods inherited from interface java.lang.Iterable
Field Detail
LeftMargin
RightMargin
TopMargin
BottomMargin
HeaderMargin
FooterMargin
PANE_LOWER_RIGHT
PANE_UPPER_RIGHT
PANE_LOWER_LEFT
PANE_UPPER_LEFT
Method Detail
createRow
removeRow
getRow
Returns the logical row (not physical) 0-based. If you ask for a row that is not defined you get a null. This is to say row 4 represents the fifth row on a sheet.
getPhysicalNumberOfRows
getFirstRowNum
Gets the first row on the sheet. Note: rows which had content before and were set to empty later might still be counted as rows by Excel and Apache POI, so the result of this method will include such rows and thus the returned value might be lower than expected!
getLastRowNum
Gets the last row on the sheet Note: rows which had content before and were set to empty later might still be counted as rows by Excel and Apache POI, so the result of this method will include such rows and thus the returned value might be higher than expected!
setColumnHidden
isColumnHidden
setRightToLeft
isRightToLeft
setColumnWidth
The maximum column width for an individual cell is 255 characters. This value represents the number of characters that can be displayed in a cell that is formatted with the standard font (first font in the workbook).
Character width is defined as the maximum digit width of the numbers 0, 1, 2, . 9 as rendered using the default font (first font in the workbook).
Unless you are using a very special font, the default character is '0' (zero), this is true for Arial (default font font in HSSF) and Calibri (default font in XSSF)
Please note, that the width set by this method includes 4 pixels of margin padding (two on each side), plus 1 pixel padding for the gridlines (Section 3.3.1.12 of the OOXML spec). This results is a slightly less value of visible characters than passed to this method (approx. 1/2 of a character).
To compute the actual number of visible characters, Excel uses the following formula (Section 3.3.1.12 of the OOXML spec):
width = Truncate([ * + ]/*256)/256 Using the Calibri font as an example, the maximum digit width of 11 point font size is 7 pixels (at 96 dpi). If you set a column width to be eight characters wide, e.g. setColumnWidth(columnIndex, 8*256) , then the actual value of visible characters (the value shown in Excel) is derived from the following equation: Truncate([numChars*7+5]/7*256)/256 = 8; which gives 7.29 .
getColumnWidth
Character width is defined as the maximum digit width of the numbers 0, 1, 2, . 9 as rendered using the default font (first font in the workbook)
getColumnWidthInPixels
Please note, that this method works correctly only for workbooks with the default font size (Arial 10pt for .xls and Calibri 11pt for .xlsx). If the default font is changed the column width can be stretched
setDefaultColumnWidth
Set the default column width for the sheet (if the columns do not define their own width) in characters
getDefaultColumnWidth
Get the default column width for the sheet (if the columns do not define their own width) in characters
getDefaultRowHeight
Get the default row height for the sheet (if the rows do not define their own height) in twips (1/20 of a point)
getDefaultRowHeightInPoints
setDefaultRowHeight
Set the default row height for the sheet (if the rows do not define their own height) in twips (1/20 of a point)
setDefaultRowHeightInPoints
getColumnStyle
Returns the CellStyle that applies to the given (0 based) column, or null if no style has been set for that column
addMergedRegion
addMergedRegionUnsafe
Adds a merged region of cells (hence those cells form one). Skips validation. It is possible to create overlapping merged regions or create a merged region that intersects a multi-cell array formula with this formula, which may result in a corrupt workbook. To check for merged regions overlapping array formulas or other merged regions after addMergedRegionUnsafe has been called, call validateMergedRegions() , which runs in O(n^2) time.
validateMergedRegions
Verify that merged regions do not intersect multi-cell array formulas and no merged regions intersect another merged region in this sheet.
setVerticallyCenter
setHorizontallyCenter
getHorizontallyCenter
getVerticallyCenter
removeMergedRegion
removeMergedRegions
getNumMergedRegions
getMergedRegion
getMergedRegions
rowIterator
setForceFormulaRecalculation
Control if Excel should be asked to recalculate all formulas on this sheet when the workbook is opened.
Calculating the formula values with FormulaEvaluator is the recommended solution, but this may be used for certain cases where evaluation in POI is not possible.
To force recalculation of formulas in the entire workbook use Workbook.setForceFormulaRecalculation(boolean) instead.
getForceFormulaRecalculation
setAutobreaks
setDisplayGuts
setDisplayZeros
Set whether the window should show 0 (zero) in cells containing zero value. When false, cells with zero value appear blank instead of showing the number zero.
isDisplayZeros
Gets the flag indicating whether the window should show 0 (zero) in cells containing zero value. When false, cells with zero value appear blank instead of showing the number zero.
setFitToPage
setRowSumsBelow
When true a summary row is inserted below the detailed data being summarized and a new outline level is established on that row.
When false a summary row is inserted above the detailed data being summarized and a new outline level is established on that row.
setRowSumsRight
Flag indicating whether summary columns appear to the right of detail in an outline, when applying an outline.
When true a summary column is inserted to the right of the detailed data being summarized and a new outline level is established on that column.
When false a summary column is inserted to the left of the detailed data being summarized and a new outline level is established on that column.
getAutobreaks
getDisplayGuts
getFitToPage
getRowSumsBelow
When true a summary row is inserted below the detailed data being summarized and a new outline level is established on that row.
When false a summary row is inserted above the detailed data being summarized and a new outline level is established on that row.
getRowSumsRight
Flag indicating whether summary columns appear to the right of detail in an outline, when applying an outline.
When true a summary column is inserted to the right of the detailed data being summarized and a new outline level is established on that column.
When false a summary column is inserted to the left of the detailed data being summarized and a new outline level is established on that column.
isPrintGridlines
Gets the flag indicating whether this sheet displays the lines between rows and columns to make editing and reading easier.
setPrintGridlines
Sets the flag indicating whether this sheet should print the lines between rows and columns to make editing and reading easier.
isPrintRowAndColumnHeadings
setPrintRowAndColumnHeadings
getPrintSetup
getHeader
Note that XSSF offers more kinds of document headers than HSSF does
getFooter
Note that XSSF offers more kinds of document footers than HSSF does.
setSelected
Note: multiple sheets can be selected, but only one sheet can be active at one time.
Returns the logical row (not physical) 0-based. If you ask for a row that is not defined you get a null. This is to say row 4 represents the fifth row on a sheet.
getPhysicalNumberOfRows
getFirstRowNum
getLastRowNum
Gets the number last row on the sheet. Owing to idiosyncrasies in the excel file format, if the result of calling this method is zero, you can't tell if that means there are zero rows on the sheet, or one at position zero. For that case, additionally call getPhysicalNumberOfRows() to tell if there is a row at position zero or not.
getDataValidations
addValidationData
setColumnHidden
isColumnHidden
setColumnWidth
The maximum column width for an individual cell is 255 characters. This value represents the number of characters that can be displayed in a cell that is formatted with the standard font (first font in the workbook).
Character width is defined as the maximum digit width of the numbers 0, 1, 2, . 9 as rendered using the default font (first font in the workbook).
Unless you are using a very special font, the default character is '0' (zero), this is true for Arial (default font font in HSSF) and Calibri (default font in XSSF)
Please note, that the width set by this method includes 4 pixels of margin padding (two on each side), plus 1 pixel padding for the gridlines (Section 3.3.1.12 of the OOXML spec). This results is a slightly less value of visible characters than passed to this method (approx. 1/2 of a character).
To compute the actual number of visible characters, Excel uses the following formula (Section 3.3.1.12 of the OOXML spec):
Using the Calibri font as an example, the maximum digit width of 11 point font size is 7 pixels (at 96 dpi). If you set a column width to be eight characters wide, e.g. setColumnWidth(columnIndex, 8*256) , then the actual value of visible characters (the value shown in Excel) is derived from the following equation: Truncate([numChars*7+5]/7*256)/256 = 8;
which gives 7.29 .
getColumnWidth
getColumnWidthInPixels
Please note, that this method works correctly only for workbooks with the default font size (Arial 10pt for .xls and Calibri 11pt for .xlsx). If the default font is changed the column width can be stretched
getDefaultColumnWidth
get the default column width for the sheet (if the columns do not define their own width) in characters
setDefaultColumnWidth
set the default column width for the sheet (if the columns do not define their own width) in characters
getDefaultRowHeight
get the default row height for the sheet (if the rows do not define their own height) in twips (1/20 of a point)
getDefaultRowHeightInPoints
setDefaultRowHeight
set the default row height for the sheet (if the rows do not define their own height) in twips (1/20 of a point)
setDefaultRowHeightInPoints
getColumnStyle
Returns the HSSFCellStyle that applies to the given (0 based) column, or null if no style has been set for that column
isGridsPrinted
setGridsPrinted
addMergedRegion
addMergedRegionUnsafe
Adds a merged region of cells (hence those cells form one). Skips validation. It is possible to create overlapping merged regions or create a merged region that intersects a multi-cell array formula with this formula, which may result in a corrupt workbook. To check for merged regions overlapping array formulas or other merged regions after addMergedRegionUnsafe has been called, call validateMergedRegions() , which runs in O(n^2) time.
validateMergedRegions
Verify that merged regions do not intersect multi-cell array formulas and no merged regions intersect another merged region in this sheet.
setForceFormulaRecalculation
Control if Excel should be asked to recalculate all formulas on this sheet when the workbook is opened.
Calculating the formula values with FormulaEvaluator is the recommended solution, but this may be used for certain cases where evaluation in POI is not possible.
It is recommended to force recalcuation of formulas on workbook level using Workbook.setForceFormulaRecalculation(boolean) to ensure that all cross-worksheet formuals and external dependencies are updated.
getForceFormulaRecalculation
Whether a record must be inserted or not at generation to indicate that formula must be recalculated when workbook is opened.
setVerticallyCenter
getVerticallyCenter
setHorizontallyCenter
getHorizontallyCenter
setRightToLeft
isRightToLeft
removeMergedRegion
removeMergedRegions
getNumMergedRegions
getMergedRegion
getMergedRegions
rowIterator
iterator
getSheet
setAlternativeExpression
setAlternativeFormula
setAutobreaks
setDialog
setDisplayGuts
setFitToPage
setRowSumsBelow
setRowSumsRight
getAlternateExpression
getAlternateFormula
getAutobreaks
getDialog
getDisplayGuts
isDisplayZeros
Gets the flag indicating whether the window should show 0 (zero) in cells containing zero value. When false, cells with zero value appear blank instead of showing the number zero.
In Excel 2003 this option can be changed in the Options dialog on the View tab.
setDisplayZeros
Set whether the window should show 0 (zero) in cells containing zero value. When false, cells with zero value appear blank instead of showing the number zero.
In Excel 2003 this option can be set in the Options dialog on the View tab.
Я пишу инструмент на Java с использованием API Apache POI для преобразования XML в MS Excel. В моем вводе XML я получаю ширину столбца в точках. Но API Apache POI имеет немного странную логику для установки ширины столбца в зависимости от размера шрифта и т. Д. (См. Документы API )
Есть ли формула для преобразования точек в ширину, как ожидается в Excel? Кто-нибудь делал это раньше?
setRowHeightInPoints() Хотя есть метод :( но нет для столбца.
PS: входной XML находится в формате ExcelML, который мне нужно преобразовать в MS Excel.
К сожалению, есть только функция setColumnWidth (int columnIndex, int width) из class Sheet ; в котором ширина - это количество символов в стандартном шрифте (первый шрифт в книге), если ваши шрифты меняются, вы не можете его использовать. Здесь объясняется, как рассчитать ширину в зависимости от размера шрифта. Формула:
Вы всегда можете использовать autoSizeColumn(int column, boolean useMergedCells) после ввода данных в свой Sheet .
Будьте осторожны при использовании autoSizeColumn() . Его можно без проблем использовать с небольшими файлами, но, пожалуйста, позаботьтесь о том, чтобы метод вызывался только один раз (в конце) для каждого столбца и не вызывался внутри цикла, что не имело бы смысла.
Пожалуйста, избегайте использования autoSizeColumn() больших файлов Excel. Метод вызывает проблемы с производительностью.
Мы использовали его в файле размером 110 тыс. Строк / 11 столбцов. Этот метод занял ~ 6 м для автоматического изменения размера всех столбцов.
Вы также можете использовать методы util, упомянутые в этом блоге: Получение ширины и высоты ячейки из Excel с помощью Apache POI . Это может решить вашу проблему.
Скопируйте и вставьте из этого блога:
Поэтому, когда вы хотите получить ширину и высоту ячейки, вы можете использовать это для получения значения в пикселях, значения приблизительно равны .
у меня возникли проблемы с получением точного размера, который я хочу с моими вычислениями для columnWidth и моей расчетной высоты строки, потому что я не понимаю документацию.
С точки зрения columnWidth, я использую строку кода sheet.setColumnWidth(int columnIndex, int width); но я не понимаю как правильно рассчитать ширину. Я понимаю, что он говорит:
поэтому у меня есть точный пример листа Excel того, что я хочу создать, и когда я выделяю столбец и выбираю ширину столбца, он говорит мне, что это 9.67 (94 pixels) . Так что же это значит? Как подключить это к моему уравнению, чтобы получить значение ширины, которое я хочу?
другая проблема, с которой я сталкиваюсь, заключается в том, что я использую код, который я нашел в другом месте (даже на SO) для динамического вычисления высоты строки. Но моя проблема в том, что я не понимаю, что mergedCellWidth в приведенном ниже коде должны быть в строку nextPos = measurer.nextOffset(mergedCellWidth) . Кажется, я не могу получить это значение правильно, и это испортит, сколько строк, по его мнению, должно быть, и поэтому моя высота строки не право.
Я думаю, что в моем случае примеры были бы лучшим ответом для меня. Спасибо!
Ну, похоже, никто не может мне помочь. После проб и ошибок, я нашел пару приближений, которые работали хорошо для меня.
по поводу моего sheet.setColumnWidth(int columnIndex, int width); проблема, я нашел хорошее приближение следующим образом:
- в Excel перейдите в" обычный " вид.
- зайти в формат -> ширина столбца. и обратите внимание на значение
- используйте следующую формулу для расчета ширины: width = ([number from step 2] * 256) + 200
это на самом деле кажется работают довольно хорошо.
по поводу моей второй проблемы о том, что mergedCellWidth должно быть, я нашел следующие работы ok для этого значения: (float) (sheet.getColumnWidth(columnIndex) / 256 * 4) . Он работает намного лучше для строк меньшей длины, и когда строки становятся больше, строка начинает становиться слишком большой (поэтому я предполагаю, что коэффициент 4 немного слишком много, но он работает для моих целей).
Я также проверил источник POI Apache для столбцов автоматической калибровки, чтобы попытаться получить представление о том, что происходит. Не много направления, хотя в том, что означают единицы, и я не смог следить за их расчетами и воспроизводить их в моем шаблоне Excel.
в Excel 2007, с файлом XSSF (xlsx), следующий код, кажется, работает отлично:
Читайте также: