I'm created an excel(xlsx) file with data.
Map<String, List<Object>> dataXlsx = new HashMap<>();
Workbook workBook = new WorkBook();
final XSSFFont blackFont = (XSSFFont) workBook.createFont();
blackFont.setFontHeightInPoints((short) 11);
blackFont.setFontName(CALIBRI);
blackFont.setBold(true);
final XSSFCellStyle blackCellStyle = (XSSFCellStyle) workBook.createCellStyle();
blackCellStyle.setFont(blackFont);
final XSSFFont redFont = (XSSFFont) workBook.createFont();
redFont.setFontHeightInPoints((short) 11);
redFont.setFontName(CALIBRI);
redFont.setBold(true);
redFont.setColor(IndexedColors.RED.getIndex());
final XSSFCellStyle redCellStyle = (XSSFCellStyle) workBook.createCellStyle();
redCellStyle.setFont(redFont);
redCellStyle.setLocked(true);
final XSSFFont blueFont = (XSSFFont) workBook.createFont();
blueFont.setFontHeightInPoints((short) 11);
blueFont.setFontName(CALIBRI);
blueFont.setBold(true);
blueFont.setColor(IndexedColors.BLUE.getIndex());
final XSSFCellStyle blueCellStyle = (XSSFCellStyle) workBook.createCellStyle();
blueCellStyle.setFont(blueFont);
final XSSFSheet newSheet = (XSSFSheet) workBook.createSheet();
final Set<String> rows = dataXlsx.keySet();
for (final String key : rows) {
...
}
}
I want read it.
When I wrote in XLSX, e.g. 3453453453 I get 3.453453453E.
https://i.stack.imgur.com/cmTgj.png
final Iterator<Row> rowIterator = sheet.iterator();
for (int i = 0; rowIterator.hasNext(); i++) {
final Row row = rowIterator.next();
final Iterator<Cell> cellIterator = row.cellIterator();
for (int k = 0; cellIterator.hasNext(); k++) {
final Cell cell = cellIterator.next();
String cellValue = cell.toString(); //set 3453453453, but get 3.45345345E
...
How can I set general format for all cells?
May be are there others any solutions?
Best regards.
I write in XLSX file the value, e.g. 'some string'(first column, first cell), 3453453453(second column, first cell) and save it on disc.
Then I reading this file in Java code with help WorkBook API. When I take first cell, get 'some string' value. When I take second cell, I get 3.453453453E value(wrong format). I Hope this help.
Best regards.
Related
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();
}
}
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();
}
}
I have a piece of code which throws me (I have made the line bold)
Exception in thread "main" java.lang.ClassCastException: org.apache.poi.hssf.usermodel.HSSFCell cannot be cast to java.lang.String
at com.codi.excel.ExcelRead.main(ExcelRead.java:36)
My code is as follows -
HSSFWorkbook wb = new HSSFWorkbook(input);
HSSFSheet sheet = wb.getSheetAt(0);
List MobileSeries=new ArrayList();
MobileSeries = findRow(sheet, cellContent);
if(MobileSeries !=null){
for(Iterator iter=MobileSeries.iterator();iter.hasNext();){
**String mobileSeries=(String)iter.next();**
String LidPattern=extractNumber(mobileSeries);
if (lid.startsWith(LidPattern)) {
System.out.println("This is a mobile number");
Could you please help me out.
Apache POI provides a handy class for you to do just that - DataFormatter
Using DataFormatter, for string cells you'll get the current contents, and for numeric or date cells the value will be formatted based on the formatting / styling rules applied to the cell, then returned as a string with that applied.
To loop over all the rows and cells in a workbook, getting their values, following the pattern in the docs, just do something like:
Workbook wb = WorkbookFactory.create(input);
Sheet sheet = wb.getSheetAt(0);
DataFormatter formatter = new DataFormatter();
for (Row r : sheet) {
for (Cell c : r) {
String value = formatter.formatCellValue(c);
}
}
Easy!
While you are iterating the rows of a worksheet, check whether the HSSFCell cell is of type String or not.
InputStream fileInputStream = null;
HSSFWorkbook hssfWorkbook;
HSSFSheet sheet;
HSSFRow row;
HSSFCell cell;
Iterator rowIterator, cellIterator;
// Put these loc in a try-catch block
fileInputStream = new FileInputStream("/path/to/TestExcel.xls");
hssfWorkbook = new HSSFWorkbook(fileInputStream);
sheet = hssfWorkbook.getSheetAt(0);
rowIterator = sheet.rowIterator();
while (rowIterator.hasNext()) {
row = (HSSFRow) rowIterator.next();
cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
cell = (HSSFCell) cellIterator.next();
if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
String someVariable = cell.getStringCellValue();
} else if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
// Handle numeric type
} else {
// Handle other types
}
}
// Other code
}
Try to access cell and extract value out of it. The below snippet should help you:
Cell cell = iter.next();
cell.getStringCellValue()
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();
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