简体   繁体   中英

How to change color of a cell of an existing excel (xlsx or xls) in java

I have requirement in that i have to read and validate the excel file and insert to data base, initially i am reading the file and inserting it to database, if the data already there in database, i am returning row and column numbers of the duplicates from database, i need to change the color of those cells based on the row and column numbers.

can any one please help me to solve this problem. or can suggest any idea how to read/ write and validate excel file, (validation in the sense i need to compare the data in the excel file with the data in the database).

currently i am using apache poi

This answer is for .xls; the API for xlsx is very similar, though. Reading the Excel file is easy, open a FileInputstream for the file, then create a HSSFWorkbook

HSSFWorkbook workbook = new HSSFWorkbook(inputStream);

To change to color of some cells, you first have to create a Style with this color (changing the style of a cell will also change some other properties, like the font etc., so things might get a bit messy here, but that's how excel works)

colorStyle = workbook.createCellStyle();
colorStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
colorStyle.setFillForegroundColor(HSSFColor.RED.index);

Now you have to loop through the rows in all workbooks, identify the duplicates, and change the style of those cells:

cell.setCellStyle(colorStyle);

Finally, you write the workbook to a new file, through a FileOutputStream

workbook.write(outputStream);

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