CellStyle is applied only upon editing cell - java

I am using this sample to change the color of a particular cell in the file
InputStream inp = new FileInputStream("C:\\temp\\vineet.xlsx");
//InputStream inp = new FileInputStream("workbook.xlsx");
Workbook wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt(0);
XSSFCellStyle style = (XSSFCellStyle) wb.createCellStyle();
XSSFCellStyle defaultStyle = (XSSFCellStyle) wb.getCellStyleAt((short) 0);
style.setFillBackgroundColor(IndexedColors.YELLOW.getIndex());
//style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
Row row = sheet.getRow(2);
Cell cell = row.getCell(3);
if (cell == null)
cell = row.createCell(3);
cell.setCellType(CellType.STRING);
cell.setCellValue("a test");
if (cell.getCellStyle().equals(defaultStyle)) {
cell.setCellStyle(style);
}
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("C:\\temp\\vineet.xlsx");
wb.write(fileOut);
fileOut.close();
at the first glance there are no changes, but when i try to edit the cell value using excel then the cell became yellow-backgrounded.

you already got the needed line to do what you need but you commented it out.
//style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
and change this:
style.setFillBackgroundColor(IndexedColors.YELLOW.getIndex());
to
style.setFillForegroundColor(IndexedColors.YELLOW.getIndex());

Related

Changing column width of a protected sheet - apache poi [duplicate]

I create an Excel file through Apache POI XSSF and I lock the sheet with a password so user can't change the value of the first two row and first five columns (I lock the sheet and allowed editing of other cells). All work fine, the only problem is that the user can't resize the column so he can neither change nor resize the columns to read all the cells value.
Is it possible to allow column resize even if the sheet is protected?
Thi is my configuration
workbook = new XSSFWorkbook();
sheet = workbook.createSheet("Sheet1");
sheet.protectSheet("passwordExcel");
unlockedNumericStyle = workbook.createCellStyle();
unlockedNumericStyle.setLocked(false);
// Format cell for date
dateStyle = workbook.createCellStyle();
CreationHelper createHelper = workbook.getCreationHelper();
dateStyle.setDataFormat(createHelper.createDataFormat().getFormat("dd/mm/yyyy"));
sheet.autoSizeColumn(1);
I read about lockFormatCell() but I don't understand if it can help me. Thanks
To be able resizing the column size while sheet is protected, you will need setting XSSFSheet.lockFormatColumns to false.
Complete example:
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
public class CreateExcelXSSFProtectedSheet {
public static void main(String[] args) throws Exception {
Workbook workbook = new XSSFWorkbook();
CreationHelper createHelper = workbook.getCreationHelper();
CellStyle unlockedNumericStyle = workbook.createCellStyle();
unlockedNumericStyle.setDataFormat(createHelper.createDataFormat().getFormat("$#,##0.00_);[Red]($#,##0.00)"));
unlockedNumericStyle.setLocked(false);
CellStyle dateStyle = workbook.createCellStyle();
dateStyle.setDataFormat(createHelper.createDataFormat().getFormat("dd/mm/yyyy"));
Sheet sheet = workbook.createSheet();
Row row = sheet.createRow(0);
Cell cell = row.createCell(1);
cell.setCellValue("some data");
row = sheet.createRow(1);
cell = row.createCell(1);
cell.setCellValue(-123456789.0123456);
cell.setCellStyle(unlockedNumericStyle);
row = sheet.createRow(2);
cell = row.createCell(1);
cell.setCellValue(new java.util.Date());
cell.setCellStyle(dateStyle);
((XSSFSheet)sheet).lockFormatColumns(false);
sheet.protectSheet("passwordExcel");
sheet.autoSizeColumn(1);
FileOutputStream out = new FileOutputStream("CreateExcelXSSFProtectedSheet.xlsx");
workbook.write(out);
out.close();
workbook.close();
}
}

Apache POI lock the cell but allow column resize

I create an Excel file through Apache POI XSSF and I lock the sheet with a password so user can't change the value of the first two row and first five columns (I lock the sheet and allowed editing of other cells). All work fine, the only problem is that the user can't resize the column so he can neither change nor resize the columns to read all the cells value.
Is it possible to allow column resize even if the sheet is protected?
Thi is my configuration
workbook = new XSSFWorkbook();
sheet = workbook.createSheet("Sheet1");
sheet.protectSheet("passwordExcel");
unlockedNumericStyle = workbook.createCellStyle();
unlockedNumericStyle.setLocked(false);
// Format cell for date
dateStyle = workbook.createCellStyle();
CreationHelper createHelper = workbook.getCreationHelper();
dateStyle.setDataFormat(createHelper.createDataFormat().getFormat("dd/mm/yyyy"));
sheet.autoSizeColumn(1);
I read about lockFormatCell() but I don't understand if it can help me. Thanks
To be able resizing the column size while sheet is protected, you will need setting XSSFSheet.lockFormatColumns to false.
Complete example:
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
public class CreateExcelXSSFProtectedSheet {
public static void main(String[] args) throws Exception {
Workbook workbook = new XSSFWorkbook();
CreationHelper createHelper = workbook.getCreationHelper();
CellStyle unlockedNumericStyle = workbook.createCellStyle();
unlockedNumericStyle.setDataFormat(createHelper.createDataFormat().getFormat("$#,##0.00_);[Red]($#,##0.00)"));
unlockedNumericStyle.setLocked(false);
CellStyle dateStyle = workbook.createCellStyle();
dateStyle.setDataFormat(createHelper.createDataFormat().getFormat("dd/mm/yyyy"));
Sheet sheet = workbook.createSheet();
Row row = sheet.createRow(0);
Cell cell = row.createCell(1);
cell.setCellValue("some data");
row = sheet.createRow(1);
cell = row.createCell(1);
cell.setCellValue(-123456789.0123456);
cell.setCellStyle(unlockedNumericStyle);
row = sheet.createRow(2);
cell = row.createCell(1);
cell.setCellValue(new java.util.Date());
cell.setCellStyle(dateStyle);
((XSSFSheet)sheet).lockFormatColumns(false);
sheet.protectSheet("passwordExcel");
sheet.autoSizeColumn(1);
FileOutputStream out = new FileOutputStream("CreateExcelXSSFProtectedSheet.xlsx");
workbook.write(out);
out.close();
workbook.close();
}
}

How to add a hyperlink in XLS cell using JAVA

I need to add a hyperlink in XLS cell which should be linked to the file in my local drive using Java. Here is my code.
I need to link the corresponding file from the local folder to the corresponding cell in the XLs.
I'd tried to add hyperlink, but i can able add only URL in the not the file from the local disk. Please help me
public boolean to_write_xls( int max, List <String> temp_1,List <String> temp_2,List <String> temp_3,List <String> temp_4,List <String> temp_5 ) {
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Analyzed Result");
HSSFRow rowhead = sheet.createRow((short) 0);
CellStyle style = workbook.createCellStyle();
style.setFillForegroundColor(HSSFColor.ORANGE.index);
style.setFillPattern(CellStyle.SOLID_FOREGROUND);
style.setBorderBottom(HSSFCellStyle.BORDER_MEDIUM);
style.setBorderTop(HSSFCellStyle.BORDER_THICK);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
rowhead.createCell((short) 0).setCellValue("Passed TC's ");
rowhead.createCell((short) 1).setCellValue("CRC:Failure ");
rowhead.createCell((short) 2).setCellValue("unexpected RRC PDU");
rowhead.createCell((short) 3).setCellValue("PCallback Error ");
rowhead.createCell((short) 4).setCellValue("Piggybacked NAS PDU");
/* for (int i=0; i<5; i++){
// sheet.setColumnWidth(i,4000);
sheet.autoSizeColumn((short)i);
}*/
Iterator<Cell> ct = rowhead.iterator();
int i=0;
while(ct.hasNext()){
Cell cell = (Cell) ct.next();
cell.setCellStyle(style);
sheet.autoSizeColumn((short)i);
i ++;
}
CellStyle style_r = workbook.createCellStyle();
style_r.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style_r.setBorderTop(HSSFCellStyle.BORDER_THIN);
style_r.setBorderRight(HSSFCellStyle.BORDER_THIN);
style_r.setBorderLeft(HSSFCellStyle.BORDER_THIN);
i=0;
while (i < max ) {
HSSFRow row = sheet.createRow((short) i+2);
row.createCell((short) 0).setCellValue(temp_1.get(i));
row.createCell((short) 1).setCellValue(temp_2.get(i));
row.createCell((short) 2).setCellValue(temp_3.get(i));
row.createCell((short) 3).setCellValue(temp_4.get(i));
row.createCell((short) 4).setCellValue(temp_5.get(i));
Iterator<Cell> rw = row.iterator();
while(rw.hasNext()){
Cell cell = (Cell) rw.next();
cell.setCellStyle(style_r);
}
i++;
}
try {
FileOutputStream Fout =
new FileOutputStream(new File(fin+"\\Result.xls"));
workbook.write(Fout);
Fout.close();
//System.out.println("Excel written successfully..with the file name directory-----> D:\\_Analyzed_Result\\Result.xls");
Runtime.getRuntime().exec("cmd /c start "+fin+"\\Result.xls");
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
Above code is not working. so I find the some other code which is working fine, which is used to add a hyperlink in the cell.
CellStyle hlink_style = workbook.createCellStyle();
Font hlink_font = workbook.createFont();
hlink_font.setUnderline(Font.U_SINGLE);
hlink_font.setColor(Font.COLOR_RED);
hlink_style.setFont(hlink_font);
Hyperlink link = createHelper.createHyperlink(Hyperlink.LINK_FILE);
Cell cell = null;
cell=row.createCell((short) 1);
cell.setCellValue("Go to Result");
path_f="D://Result.xls";
link.setAddress(path_f);
cell.setHyperlink(link);
cell.setCellStyle(hlink_style);
It works 100% fine!!
Developers can add hyperlinks to external Excel files by calling the Add method of Hyperlinks collection. The Add method takes the following parameters:
Cell Name , represents the cell name where the hyperlink will be added
Number of Rows , represents the number of rows in this hyperlink range
Number of Columns , represents the number of columns of this hyperlink range
URL , represents the address of the external Excel file that will be used as a hyperlink
[Java]
//Instantiating a Workbook object
Workbook workbook = new Workbook();
//Obtaining the reference of the first worksheet.
WorksheetCollection worksheets = workbook.getWorksheets();
Worksheet sheet = worksheets.get(0);
//Setting a value to the "A1" cell
Cells cells = sheet.getCells();
Cell cell = cells.get("A1");
cell.setValue("Visit Aspose");
//Setting the font color of the cell to Blue
Style style = cell.getStyle();
style.getFont().setColor(Color.getBlue());
//Setting the font of the cell to Single Underline
style.getFont().setUnderline(FontUnderlineType.SINGLE);
cell.setStyle(style);
HyperlinkCollection hyperlinks = sheet.getHyperlinks();
//Adding a link to the external file
hyperlinks.add("A5", 1, 1, "C:\\book1.xls");
//Saving the Excel file
workbook.save("c:\\book2.xls");
You can create hyperlink in excel sheet using this java code
File veri1 = new File("your_ file_path");
FileInputStream inputStream_ED1 = new FileInputStream(veri1);
HSSFWorkbook workbook_ED1 = new HSSFWorkbook(inputStream_ED1);
HSSFSheet sheet_ED1 = workbook_ED1.getSheet("Result");
CreationHelper createHelper = workbook_ED1.getCreationHelper();
HSSFCellStyle hlinkstyle = workbook_ED1.createCellStyle();
HSSFFont hlinkfont = workbook_ED1.createFont();
hlinkfont.setUnderline(HSSFFont.U_SINGLE);
hlinkfont.setColor(HSSFColor.BLUE.index);
hlinkstyle.setFont(hlinkfont);
Iterator<Row> riterator_ED1 = sheet_ED1.iterator();
Row row_ED1 = sheet_ED1.createRow(sheet_ED1.getLastRowNum()+1);
if(sheet_ED1.getLastRowNum()==0){
}
Cell DeviceName = row_ED1.createCell(0);
DeviceName.setCellValue(DeviceID.toString());
Cell Module = row_ED1.createCell(1);
Module.setCellValue(module.toString());
Cell SubModule1 = row_ED1.createCell(2);
SubModule1.setCellValue(SubModule.toString());
Cell ScenarioID1 = row_ED1.createCell(3);
ScenarioID1.setCellValue(ScenarioID.toString());
Cell TestcaseID = row_ED1.createCell(4);
TestcaseID.setCellValue(TestCaseID.toString());
Cell TCDescription = row_ED1.createCell(5);
TCDescription.setCellValue(testcasedis.toString());
Cell ExpectedResult1 = row_ED1.createCell(6);
ExpectedResult1.setCellValue(ExpectedResult.toString());
Cell ActualResult1 = row_ED1.createCell(7);
ActualResult1.setCellValue(ActualResult.toString());
Cell Status1 = row_ED1.createCell(8);
Status1.setCellValue(Status.toString());
Cell time = row_ED1.createCell(9);
time.setCellValue(Time.toString());
Cell ExecutionDate1 = row_ED1.createCell(10);
ExecutionDate1.setCellValue(ExecutionDate.toString());
HSSFHyperlink link = (HSSFHyperlink)createHelper.createHyperlink(Hyperlink.LINK_URL);
Cell ss = row_ED1.createCell((short) 11);
ss.setCellValue(sspath.toString());
link = (HSSFHyperlink)createHelper.createHyperlink(Hyperlink.LINK_FILE);
link.setAddress(sspath.toString());
ss.setHyperlink(link);
ss.setCellStyle(hlinkstyle);
FileOutputStream
os_ED1 = new FileOutputStream(veri1);
workbook_ED1.write(os_ED1);
os_ED1.close();
workbook_ED1.close();
inputStream_ED1.close();

Write number in excel cells using Apache POI

How can I write my full value in cell with help of poi ?
i.e. if value is 1000.000 then how can I write this full value without truncating 000 after "." with POI? means I want full value.
In my case, it only takes 1000 but this is not right format for me.
You have to set "Format" of the cell where this number is getting stored. Example code:
Workbook wb = new HSSFWorkbook();
Sheet sheet = wb.createSheet("format sheet");
CellStyle style;
DataFormat format = wb.createDataFormat();
Row row;
Cell cell;
short rowNum = 0;
short colNum = 0;
row = sheet.createRow(rowNum++);
cell = row.createCell(colNum);
cell.setCellValue(11111.25);
style = wb.createCellStyle();
style.setDataFormat(format.getFormat("0.0"));
cell.setCellStyle(style);
row = sheet.createRow(rowNum++);
cell = row.createCell(colNum);
cell.setCellValue(11111.25);
style = wb.createCellStyle();
style.setDataFormat(format.getFormat("#,##0.0000"));
cell.setCellStyle(style);
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
Source : http://poi.apache.org/spreadsheet/quick-guide.html#DataFormats

Making excel sheet read only

I want read only excel sheet after creating it using Apache POI HSSF. How can I do that?
A detailed description can be found here:
http://systeminetwork.com/article/locking-cells-hssf
Basically you have to assign your cells a custom CellStyle with CellStyle.setLocked(true)
Edited
Hi Gaurav,
here is the complete and working code:
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("sheet1");
/* password required for locks to become effective */
sheet.protectSheet("secretPassword");
/* cell style for locking */
CellStyle lockedCellStyle = workbook.createCellStyle();
lockedCellStyle.setLocked(true);
/* cell style for editable cells */
CellStyle unlockedCellStyle = workbook.createCellStyle();
unlockedCellStyle.setLocked(false);
/* cell which will be locked */
Cell lockedCell = sheet.createRow(0).createCell(0);
lockedCell.setCellValue("Hi, I'm locked...");
lockedCell.setCellStyle(lockedCellStyle);
/* unlocked cell */
Cell unlockedCell = sheet.createRow(1).createCell(0);
unlockedCell.setCellValue("Just edit me...");
unlockedCell.setCellStyle(unlockedCellStyle);
OutputStream out = new FileOutputStream("sample.xls");
workbook.write(out);
out.flush();
out.close();
Here is some tested code that works in making the specific cell readonly. Based on your comment in #Thomas Weber's answer.
This sets an initial value in a cell, then it uses a data constraint to ensure that fixed value cannot be modified by the user in Excel. Try it out.
HSSFWorkbook workBook = new HSSFWorkbook ();
HSSFSheet sheet1 = workBook.createSheet();
HSSFRow row1 = sheet1.createRow(10);
HSSFCell cell1 = row1.createCell(0);
cell1.setCellValue("text: The new line which should be locked"); // SETTING INITIAL VALUE
HSSFCell displayNameCell = cell1;
String[] displayNameList = new String[]{"text: The new line which should be locked"}; //ADDING SAME VALUE INTO A STRING ARRAY AS THE RESTRICTED VALUE
DVConstraint displayNameConstraint = DVConstraint.createExplicitListConstraint(displayNameList);
CellRangeAddressList displayNameCellRange = new CellRangeAddressList(displayNameCell.getRowIndex(),displayNameCell.getRowIndex(),displayNameCell.getColumnIndex(),displayNameCell.getColumnIndex());
HSSFDataValidation displayNameValidation = new HSSFDataValidation(displayNameCellRange,displayNameConstraint);
displayNameValidation.createErrorBox("Not Applicable","Cannot change the value");
displayNameValidation.setSuppressDropDownArrow(true);
displayNameCell.getSheet().addValidationData(displayNameValidation);
// Write the output to a file
FileOutputStream fileOut1 = new FileOutputStream("D:\\book.xls");
workBook.write(fileOut1);
fileOut1.close();
This code is based on this thread http://osdir.com/ml/user-poi.apache.org/2009-07/msg00056.html
new File("/path/to/file.xls").setReadOnly();

Categories