这个简单的教程将详细说明如何使用 Java 调整 Excel 中的列宽。我们可以在 Excel 中拥有各种长度可能不同的数据,并且需要调整列大小才能正确显示。您将在此处学习使用 Java **调整 Excel 中的列大小的过程,并借助分步说明和可立即运行的 Java 代码将输出文件另存为 XLSX。
使用 Java 在 Excel 中调整列宽的步骤
- 使用 Maven 存储库,在应用程序中添加对 Aspose.Cells 库的引用
- 将 Excel 文件加载到要调整其列大小的 Workbook 对象中
- 从工作簿中的工作表集合访问所需的 worksheet 引用
- 从工作表中获取对 Cells 集合的引用以设置单个列的大小
- 通过提供列号和所需宽度来设置特定列的宽度
- 直接使用工作表对象,根据内容大小自动调整特定或多个列
- 使用调整大小的列保存更新的 Excel 文件
在这里,我们已经看到使用 Java 修改 Excel 列宽,我们加载目标 Excel 文件,然后访问其中所需的工作表。如果要使用固定值设置列宽,可以使用工作表中的 Cells 集合,如果要根据每个单元格中的内容自动调整宽度,可以使用 autoFitColumn() 和 autoFitColumns() 函数工作表类。
使用Java在Excel中设置列宽的代码
import com.aspose.cells.License; | |
import com.aspose.cells.Cells; | |
import com.aspose.cells.Workbook; | |
import com.aspose.cells.Worksheet; | |
public class AdjustColumnWidthInExcelUsingJava { | |
public static void main(String[] args) throws Exception {//main function to exercise setting width of columns | |
// Initialize the license to avoid watermark in the output workbook after setting columns width | |
License cellsLicenseForColumnWidth = new License(); | |
cellsLicenseForColumnWidth.setLicense("Aspose.Cells.lic"); | |
// Open the workbook whose column widths are to be set | |
Workbook sampleWb = new Workbook("InputWorkbookForReesizingColumns.xlsx"); | |
// Access the desired worksheet reference say second sheet | |
Worksheet worksheet2 = sampleWb.getWorksheets().get(1); | |
// Access the cells collection from the selected worksheet | |
Cells cellsSheet2 = worksheet2.getCells(); | |
// Set the third column's width to 20.0 | |
cellsSheet2.setColumnWidth(2, 20.0); | |
// Set a column width (say 4th column) based on the data in it | |
worksheet2.autoFitColumn(3); | |
// Set column width for a range of columns | |
worksheet2.autoFitColumns(10,19); | |
// Save the output Excel file after setting the column width of different sheets | |
sampleWb.save("OutputWorkbookWithModifiedColumnSize.xlsx"); | |
} | |
} |
这个简短的代码演示了通过使用 Cells.setColumnWidth() 函数并提供列索引和描述确切宽度的双精度值来更改宽度的过程。同样,要根据内容更改单列大小,您可以通过提供列号来调用 Worksheet.autoFitColumn()。要设置工作表中多列的宽度,请调用 Worksheet.autoFitColumns() 以及开始和结束列号。
这个简单的教程解释了如何使用 java 在 excel 中更改列的宽度。如果您想了解此产品的其他功能,例如将输出文件保存为 PDF,请参阅 如何在 Java 中从 Excel 生成 PDF 上的文章。