简体   繁体   中英

Formatting Excel Spreadsheet using Apache POI in JAVA

My intention is to set the border for the contents of the spreadsheet data while maintaining the other properties of the cell as it is.

The below code formats(setting border) the whole spreadsheet rather than formatting only the portion of spreadsheet where there is actual data.

Is there a reason why the formatting is applied throughout the spreadsheet? And is there a way to overcome this?

package learning.selenium.self.begining;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Iterator;

import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

public class testing {

    public static void main(String[] args) throws Exception {
        File myFile = new File("TestFile.xlsx");
        Workbook myWorkbook = WorkbookFactory.create(new FileInputStream(myFile));
        Sheet mySheet = myWorkbook.getSheetAt(0);

        Iterator<Row> r = mySheet.rowIterator();
        while (r.hasNext()) {
            Row myR = r.next();
            Iterator<Cell> c = myR.cellIterator();
            while (c.hasNext()) {
                Cell myC = c.next();
                System.out.println("precessing (" + myR.getRowNum() + "," + myC.getColumnIndex() + ")");
                CellStyle s = myC.getCellStyle();
                s = myC.getCellStyle();
                s.setBorderBottom(BorderStyle.THIN);
                s.setBorderTop(BorderStyle.THIN);
                s.setBorderLeft(BorderStyle.THIN);
                s.setBorderRight(BorderStyle.THIN);
                myC.setCellStyle(s);
            }
        }

        FileOutputStream fos = new FileOutputStream(myFile);
        myWorkbook.write(fos);
        fos.close();
    }
}

I dont know if this helps but is worth checking out

CellRangeAddress range= new CellRangeAddress(firstrow, lastrow, firstcol, lastcol); 

RegionUtil.setBorderBottom(BorderStyle.THIN, range, sheet);

Same way u can set for other borders.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM