Baseline
We wish to edit a xls file with 5 colum titles but we want the two last columns with a different rotation.
... HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet sheet = workbook.createSheet(); HSSFRow row = null; HSSFCell cellTitre = null; //Style cell HSSFCellStyle style = workbook.createCellStyle(); //data for titles String [][] excelData = new String [0][5] excelData[0][0]="Title1"; excelData[0][1]="Title2"; excelData[0][2]="Title3"; excelData[0][3]="Title4"; excelData[0][4]="Title5"; ... //Insert titles for (int rowNum = 0; rowNum < excelData.length; rowNum++){ //just one row row = sheet.createRow(rowNum); for (int cellNum = 0; cellNum < excelData[0].length ; cellNum++){ cellTitre = row.createCell((short) cellNum); if(cellNum==3 || cellNum==4){ styleTitre.setRotation((short)-90); } cellTitre.setCellStyle(styleTitre); cellTitre.setCellValue(new HSSFRichTextString( excelData[rowNum][cellNum])); } } ...
Problem
That sets rotation for all titles !
Error
Solution
Create two differents HSSFCellStyle.
Remark : don’t do as below !
//Style cell HSSFCellStyle style = workbook.createCellStyle(); ... HSSFCellStyle style2 = workbook.createCellStyle(); style2=style; //Error - two pointers for the same object style2.setRotation((short)-90); ...
In java "style2=style;" means you add a new name to call the same object with same parameters.
... HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet sheet = workbook.createSheet(); HSSFRow row = null; HSSFCell cellTitre = null; //Style cell HSSFCellStyle style = workbook.createCellStyle(); ...//add font into style etc... style.setRotation((short)0); //Style2 cell HSSFCellStyle style2 = workbook.createCellStyle(); ...//add font into style etc... even if it's same as the first style style.setRotation((short)-90); //data for titles String [][] excelData = new String [0][5] excelData[0][0]="Title1"; excelData[0][1]="Title2"; excelData[0][2]="Title3"; excelData[0][3]="Title4"; excelData[0][4]="Title5"; ... //Insert titles for (int rowNum = 0; rowNum < excelData.length; rowNum++){ //just one row row = sheet.createRow(rowNum); for (int cellNum = 0; cellNum < excelData[0].length ; cellNum++){ cellTitre = row.createCell((short) cellNum); if(cellNum==3 || cellNum==4){ cellTitre.setCellStyle(styleTitre2); } else cellTitre.setCellStyle(styleTitre); cellTitre.setCellValue(new HSSFRichTextString( excelData[rowNum][cellNum])); } } ...