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();
Related
Hi i am new to writing data to excel however after doing much research and reading documentation I have done it.
My Problem:
When string data is stored in my array and written it to excel however it does not put it in one column (which is what I want) it spaces each string out in a column to the right of it in a diagonal descent in my spread sheet. A picture is below.
What I want is for each string/name to be put in one column under each other. Any suggestions would be appreciated.
Code Snippet:
System.out.println("Write data to an Excel Sheet");
FileOutputStream out = new FileOutputStream("C:/Users/hoflerj/Desktop/text2excel/finish.xlsx");
XSSFWorkbook workBook = new XSSFWorkbook();
XSSFSheet spreadSheet = workBook.createSheet("clientid");
XSSFRow row;
XSSFCell cell;
for(int i=0;i<arr.size();i++){
row = spreadSheet.createRow((short) i);
cell = row.createCell(i);
System.out.println(arr.get(i));
cell.setCellValue(arr.get(i).toString());
}
System.out.println("Done");
workBook.write(out);
arr.clear();
out.close();
You are increasing column index as well.
Just change from:
cell = row.createCell(i);
To:
cell = row.createCell(0);
So the For Loop will be like:
for(int i=0;i<arr.size();i++){
row = spreadSheet.createRow((short) i);
cell = row.createCell(0);
System.out.println(arr.get(i));
cell.setCellValue(arr.get(i).toString());
}
Or with fewer lines:
for(int i=0;i<arr.size();i++){
row = spreadSheet.createRow((short) i);
row.createCell(0).setCellValue( arr.get(i).toString() );
System.out.println(arr.get(i));
}
I have written a program that reads Excel template sheet. In which the first column was hidden. Now, I have a code that un-hide the excel column programmatically (so Column start from A1).
I'm using Apache POI 3.16 version.
When I open a file, it should show me a column from A1 instead it shows me from B1 column.
When I write below code for XLS, It working properly but didn't work for an XLSX format.
sheet.showInPane(0, 0);
I need to manually move the horizontal scroll bar to view my first column. How should I achieve this programmatically to auto-scroll to the first column for XLSX format?
Here is my full code.
public Workbook readWorkBookAndWriteErrors(String bufId,String inputFile, String ext) throws Exception {
Workbook workBook =null;
Sheet sheet = null;
if(GlobalVariables.EXCEL_FORMAT_XLS.equalsIgnoreCase(ext)){
// Get the workbook instance for XLS file
workBook = new HSSFWorkbook(new FileInputStream(inputFile));
}else{
// Get the workbook instance for XLSX file
workBook = new XSSFWorkbook(new FileInputStream(inputFile));
}
sheet = workBook.getSheetAt(0);
Row row = null;
if(sheet.isColumnHidden(0)){
sheet.setColumnHidden(0, false);
sheet.setActiveCell(new CellAddress("A1"));
sheet.showInPane(0, 0);
sheet.createFreezePane(0, 1);
Iterator<Row> rowIterator = sheet.iterator();
int rowIndex = 1;
while (rowIterator.hasNext()) {
row = rowIterator.next();
if(rowIndex == 1){
rowIndex++;
continue;
}
Cell cell = row.createCell(0);
cell.setCellValue("error message");
rowIndex++;
}
}
return workBook;
}
Here is the answer to my question. Please refer this Source
public Workbook readWorkBookAndWriteErrors(String bufId,String inputFile, String ext) throws Exception {
Workbook workBook =null;
Sheet sheet = null;
if(GlobalVariables.EXCEL_FORMAT_XLS.equalsIgnoreCase(ext)){
// Get the workbook instance for XLS file
workBook = new HSSFWorkbook(new FileInputStream(inputFile));
}else{
// Get the workbook instance for XLSX file
workBook = new XSSFWorkbook(new FileInputStream(inputFile));
}
sheet = workBook.getSheetAt(0);
Row row = null;
if(sheet.isColumnHidden(0)){
sheet.setColumnHidden(0, false);
if(sheet instanceof XSSFSheet){
CTWorksheet ctWorksheet = null;
CTSheetViews ctSheetViews = null;
CTSheetView ctSheetView = null;
XSSFSheet tempSheet = (XSSFSheet) sheet;
// First step is to get at the CTWorksheet bean underlying the worksheet.
ctWorksheet = tempSheet.getCTWorksheet();
// From the CTWorksheet, get at the sheet views.
ctSheetViews = ctWorksheet.getSheetViews();
// Grab a single sheet view from that array
ctSheetView = ctSheetViews.getSheetViewArray(ctSheetViews.sizeOfSheetViewArray() - 1);
// Se the address of the top left hand cell.
ctSheetView.setTopLeftCell("A1");
}else{
sheet.setActiveCell(new CellAddress("A1"));
sheet.showInPane(0, 0);
}
Iterator<Row> rowIterator = sheet.iterator();
int rowIndex = 1;
while (rowIterator.hasNext()) {
row = rowIterator.next();
if(rowIndex == 1){
rowIndex++;
continue;
}
Cell cell = row.createCell(0);
cell.setCellValue("error message");
rowIndex++;
}
}
return workBook;
}
If you are using latest C# NPOI, I made this utility function:
/// <summary>Set view position at given coordinates.</summary>
/// <param name="sheet">A reference to the Excel sheet.</param>
/// <param name="topLeftCell">The coordinates of the cell that will show in top left corner when you open the Excel sheet (example: "A1").</param>
/// <param name="onlyFirstView">If true, only first sheet view will have position adjusted. If false, every views from the sheet will have have position adjusted.</param>
public static void SetViewPosition(ref NPOI.SS.UserModel.ISheet sheet, string topLeftCell = "A1", bool onlyFirstView = true)
{
NPOI.OpenXmlFormats.Spreadsheet.CT_Worksheet worksheet = (NPOI.OpenXmlFormats.Spreadsheet.CT_Worksheet)(typeof(NPOI.XSSF.UserModel.XSSFSheet).GetField("worksheet", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)?.GetValue((NPOI.XSSF.UserModel.XSSFSheet)sheet));
if (worksheet?.sheetViews?.sheetView != null && worksheet.sheetViews.sheetView.Count > 0)
{
if (onlyFirstView)
worksheet.sheetViews.sheetView[0].topLeftCell = topLeftCell;
else
foreach (NPOI.OpenXmlFormats.Spreadsheet.CT_SheetView view in worksheet.sheetViews.sheetView)
view.topLeftCell = topLeftCell;
}
}
Usage example:
NPOI.SS.UserModel.ISheet mySheet = myWorkbook.GetSheetAt(0);
// First sheet from our workbook opens with view set to top left corner (cell A1 visible in top left corner).
SetViewPosition(ref mySheet, "A1");
Below code worked for me to move horizontal scrollbar to required position.
Used apache poi libraries(poi, poi-ooxml).
((XSSFSheet)sheet).getCTWorksheet().getSheetViews().getSheetViewArray(0).setTopLeftCell("AE11");
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());
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
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();