Java sets Excel adaptive row height and column width

In excel, it is a common method to adjust the overall layout of the table quickly by setting the adaptive row height or column width. When setting the adaption, two situations can be considered:
1. Fixed data, set row height and column width adaptive data (common setting adaptive method)
2. Fix the column width and reduce the data font size to fit the column width
This article will introduce the specific adaptive setting method through java program.
 
Tools: free flame.xls for Java (free version)
Note: it can be accessed through the official website Download package , and unzip the jar file under the lib folder into the java program; or maven warehouse Download And import.
Refer to the following import effect:

 


 

Java code example

1. Fixed data, set row height and column width adaptive data

(this adaptive method can be set for the specified cell data or the whole worksheet)

import com.spire.xls.*;

public class AutoFit {
    public static void main(String[] args) {
        //Create a Workbook Class and load the test document
        Workbook wb = new Workbook();
        wb.loadFromFile("sample.xlsx");

        //Get worksheet
        Worksheet sheet = wb.getWorksheets().get(0);

        //Set row height and column width as adaptive (applied to specified data range)
        sheet.getAllocatedRange().get("A1:E14").autoFitRows();
        sheet.getAllocatedRange().get("A1:E14").autoFitColumns();

        /*//Set row height and column width to adaptive (applies to the entire worksheet)
        sheet.getAllocatedRange().autoFitRows();
        sheet.getAllocatedRange().autoFitColumns();*/

        //Save document
        wb.saveToFile("result.xlsx", FileFormat.Version2010);
        wb.dispose();
    }
}

Adaptive setting effect:

 

2. Reduce the data font size to fit the column width

import com.spire.xls.*;

public class ShrinkToFit {
    public static void main(String[] args) {
        Workbook wb = new Workbook();
        wb.loadFromFile("test.xlsx");
        //Get the first sheet
        Worksheet sheet = wb.getWorksheets().get(0);

        //Specifies the range of cells that need to automatically shrink the font
        CellRange cell = (CellRange) sheet.get("A1");

        //Set up ShrinkToFit by true,Shrink data to fit cells
        cell.getStyle().setShrinkToFit(true);

        //Save document
        wb.saveToFile("ShrinkTextToFitCell.xlsx", ExcelVersion.Version2013);
        wb.dispose();
    }
}

Text reduction effect:




(end of this paper)

Tags: Java Excel Maven

Posted on Tue, 11 Feb 2020 10:18:48 -0800 by jwcsk8r