I am writting some text say "Pass" into excel file using cell.setCellValue("Pass"). Now I have to create a link to an image which locates at directory (C:\Users\UserName\DeskTop\image\test.jpg) from an excel.
When I click on text pass from excel file, then it should open the test.jpg image.
Please guide me/share to JAVA code to achieve this.
Thanks,
Md Ashfaq
Ashfaq...Following is a method you can user for hyperlink the screenshot with the cell.
public static void hyperlinkScreenshot(XSSFCell cell, String FileAddress){
XSSFWorkbook wb=cell.getRow().getSheet().getWorkbook();
CreationHelper createHelper = wb.getCreationHelper();
CellStyle hlink_style = wb.createCellStyle();
Font hlink_font = wb.createFont();
hlink_font.setUnderline(Font.U_SINGLE);
hlink_font.setColor(IndexedColors.BLUE.getIndex());
hlink_style.setFont(hlink_font);
Hyperlink hp = createHelper.createHyperlink(Hyperlink.LINK_FILE);
FileAddress=FileAddress.replace("\\", "/");
hp.setAddress(FileAddress);
cell.setHyperlink(hp);
cell.setCellStyle(hlink_style);
}
for details check here.
Cell.Hyperlinks.Add Anchor:=Selection, Address:= _
"C:\Users\UserName\DeskTop\image\test.jpg", TextToDisplay:="pass"
You can remove the setvalue as TextToDisplay can handle this...
Related
Sorry my English not good.
My code: styledate
CreationHelper createHelper = workbook.getCreationHelper();
styledate.setDataFormat(
createHelper.createDataFormat().getFormat("d-mmm"));
When I create a excel file, the cell set styledate not display "16-Jun". It's "06/16/2018".
If I create input on excel file, it's ok "16-Jun".
I want when I create file, cell will display "16-Jun". Thank for your help.
Whether a cell style will work or not depends on the cell value set into the cell. Your creating of the style looks correct but you do not show how you are setting the cell value into the cell. The style can only work if the cell value is a date value. If it is a string value, then the style cannot work.
The following complete example shows the problem:
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class CreateExcelCustomDateFormat {
public static void main(String[] args) throws Exception {
Workbook workbook = new XSSFWorkbook();
CreationHelper createHelper = workbook.getCreationHelper();
CellStyle styledate = workbook.createCellStyle();
styledate.setDataFormat(createHelper.createDataFormat().getFormat("d-MMM"));
Sheet sheet = workbook.createSheet();
Cell cell;
//This sets date value into cell and does formatting it.
cell = sheet.createRow(0).createCell(0);
cell.setCellValue(java.util.Date.from(java.time.Instant.now()));
cell.setCellStyle(styledate);
String date = "06/17/2018";
//This sets string value into cell. There the format will not work.
cell = sheet.createRow(1).createCell(0);
cell.setCellValue(date);
cell.setCellStyle(styledate);
//This converts string value to date and then sets the date into cell. There the format will work.
cell = sheet.createRow(2).createCell(0);
cell.setCellValue(java.util.Date.from(
java.time.LocalDate.parse(
date,
java.time.format.DateTimeFormatter.ofPattern("MM/dd/yyyy")
).atStartOfDay(java.time.ZoneId.systemDefault()).toOffsetDateTime().toInstant()
)); //yes, java.time is a monster in usage ;-)
cell.setCellStyle(styledate);
try (FileOutputStream fos = new FileOutputStream("CreateExcelCustomDateFormat.xlsx")) {
workbook.write(fos);
workbook.close();
}
}
}
I am trying to change the default cell style for an entire Excel workbook (XSSF) using Apache POI. This should be applied to new cells a user might create (after the workbook has been saved by POI). I am trying to do this by calling workbook.getCellStyleAt(0) -- which I understand to be the default style for the workbook -- and then by modifying this style to what I want for the new default.
This works when I read in an existing XSLX file (a "template" file) and modify the default style. But when I create a new XSLX file from scratch using POI, it does not work.
When stepping through using a debugger I can see that, when using a "template" file, there is a "theme" assigned to the cell style at index 0 (probably because the template file was originally created using Excel). But when creating a file from scratch (using POI), the cell style at index 0 has a null theme. (This might be a factor in why this works using one approach but not the other.)
Any suggestions on how to reliably change the default cell style for a workbook (XSSF) regardless of how the workbook was originally created? Thanks!
There are two possibilities to achieve this with XSSF.
First: If you select all cells in a XSSF worksheet in Excel and apply a style to them, then a cols element is added to the sheet with a style definition for all columns:
<cols>
<col min="1" max="16384" style="1"/>
</cols>
This can be achieved with apache poi like so:
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import java.io.FileOutputStream;
import java.io.IOException;
class ExcelCellStyleAllColumns
{
public static void main(String[] args) {
try {
Workbook wb = new XSSFWorkbook();
Font font = wb.createFont();
font.setFontHeightInPoints((short)24);
font.setFontName("Courier New");
font.setItalic(true);
font.setBold(true);
CellStyle style = wb.createCellStyle();
style.setFont(font);
Sheet sheet = wb.createSheet();
org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCol cTCol =
((XSSFSheet)sheet).getCTWorksheet().getColsArray(0).addNewCol();
cTCol.setMin(1);
cTCol.setMax(16384);
cTCol.setWidth(12.7109375);
cTCol.setStyle(style.getIndex());
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("test");
cell.setCellStyle(style);
FileOutputStream os = new FileOutputStream("ExcelCellStyleAllColumns.xlsx");
wb.write(os);
os.close();
} catch (IOException ioex) {
}
}
}
This will change the default cell style of all cells in the sheet.
Second: You can modify the style definitions of the normal cell style like so:
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import java.io.FileOutputStream;
import java.io.IOException;
class ExcelDefaultCellStyle {
public static void main(String[] args) {
try {
Workbook wb = new XSSFWorkbook();
Font font = wb.getFontAt((short)0);
font.setFontHeightInPoints((short)24);
font.setFontName("Courier New");
((XSSFFont)font).setFamily(3);
((XSSFFont)font).setScheme(FontScheme.NONE);
font.setItalic(true);
font.setBold(true);
CellStyle style = wb.getCellStyleAt(0);
style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
style.setWrapText(true);
((XSSFWorkbook) wb).getStylesSource().getCTStylesheet().addNewCellStyles().addNewCellStyle().setXfId(0);
((XSSFCellStyle)style).getStyleXf().addNewAlignment().setVertical(
org.openxmlformats.schemas.spreadsheetml.x2006.main.STVerticalAlignment.CENTER);
((XSSFCellStyle)style).getStyleXf().getAlignment().setWrapText(true);
Sheet sheet = wb.createSheet();
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("test");
FileOutputStream os = new FileOutputStream("ExcelDefaultCellStyle.xlsx");
wb.write(os);
os.close();
} catch (IOException ioex) {
}
}
}
This will change the default cell style of all cells in the whole workbook.
The XML in styles.xml shows:
<cellStyleXfs count="1">
<xf numFmtId="0" fontId="0" fillId="0" borderId="0">
<alignment vertical="center" wrapText="true"/>
</xf>
</cellStyleXfs>
<cellXfs count="1">
<xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0">
<alignment vertical="center" wrapText="true"/>
</xf>
</cellXfs>
<cellStyles>
<cellStyle xfId="0"/>
</cellStyles>
As you see the normal cell style is the first one in cellStyles. It refers to xfId="0" which refers to numFmtId="0" fontId="0" fillId="0" borderId="0". That means the very first definitions of number format, font, fill format and border is used in normal cell style.
I am using java workbook xls but i am unable to set the color.I am using the following code.
CellStyle cellStyle = sheet.getWorkbook().createCellStyle();
cellStyle.setFillBackgroundColor(HSSFColor.DARK_RED.index);
Cell celli = row0.createCell((short) i);
celli.setCellValue(list.get(i).toString());
celli.setCellStyle(cellStyle);
I am using the cellstyle but color is not being set.
You should use
cellStyle.setFillForegroundColor(HSSFColor.DARK_RED.index);
cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
instead of
cellStyle.setFillBackgroundColor(HSSFColor.DARK_RED.index);
I am getting Number stored as text warning for the created excel file using POI. I am trying to display percentage. This question discusses the same, but it's for python. Can some one please suggest me how to avoid this in java using POI?
Below are the lines where I get this warning.
workbook= new XSSFWorkbook();
sh1 = wb.createSheet("Data Sheet");
cell = row.createCell(3);
cell.setCellValue(37 + "%");
Based on Gagravarr answer I did it this way.
XSSFDataFormat df = workbook.createDataFormat();
CellStyle cs = wb.createCellStyle();
cs.setDataFormat(df.getFormat("%"));
cell.setCellValue(0.37);
cell.setCellStyle(cs);
But it just shows up as 0.37 with no warning now, not 37%.
You're getting the warning because, as it says, you're storing a number as text.
What you probably want to do is:
CellStyle cs = wb.createCellStyle();
cs.setDataFormat(df.getFormat("%"));
cell.setCellValue(0.37);
cell.setCellStyle(cs);
That will store the number 37 as a number, and tell excel to apply a percentage format string to it. Oh, and since 37% is 0.37, you need to store 0.37 not 37!
Edit By popular request, here's a standalone program you can use to see it in action, for both .xls and .xlsx files. Tested with POI 3.10 final, and with all the required dependencies and component jars on the classpath.
public class TestPercent {
public static void main(String[] args) throws Exception {
System.out.println("Generating...");
for (Workbook wb : new Workbook[] {new HSSFWorkbook(), new XSSFWorkbook()}) {
Sheet sheet = wb.createSheet("Data Sheet");
Row row = sheet.createRow(0);
Cell cell = row.createCell(3);
DataFormat df = wb.createDataFormat();
CellStyle cs = wb.createCellStyle();
cs.setDataFormat(df.getFormat("%"));
cell.setCellValue(0.37);
cell.setCellStyle(cs);
String output = "/tmp/text.xls";
if (wb instanceof XSSFWorkbook) { output += "x"; }
FileOutputStream out = new FileOutputStream(output);
wb.write(out);
out.close();
}
System.out.println("Done");
}
}
Try also setting the CellType:
cell.setCellType(Cell.CELL_TYPE_NUMERIC);
if(NumberUtils.isDigits(text)){
titleCell.setCellValue(Integer.parseInt(text));
}else{
titleCell.setCellValue(text);
}
XSSFWorkbook xSSFWorkbook = new XSSFWorkbook();
CreationHelper createHelper = xSSFWorkbook.getCreationHelper();
XSSFCellStyle numberStyle = xSSFWorkbook.createCellStyle();
numberStyle.setDataFormat(createHelper.createDataFormat().getFormat("###.00"));
double d = 50.0;
XSSFRow dataRow = sheet.createRow(1);
Cellcel1 = dataRow.createCell(1);
cel1.setCellValue(d);
This may be a bit old but try this:
df.getFormat("0.00%")
I am a beginner with Apache POI library.
in VBA, I know I can select and bold the whole worksheet with following code
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets(1)
ws.Cells.Font.Bold = True
May I know how to select and bold the whole sheet by coding with Apache POI library?
thanks
There is a pretty good example on this link.
Sheet sheet = wb.createSheet("test");
CellStyle cs = wb.createCellStyle();
Font f = wb.createFont();
f.setBoldweight(Font.BOLDWEIGHT_BOLD);
cs.setFont(f);
sheet.setDefaultColumnStyle(1,cs); //set bold for column 1
The default font for a workbook can be retrieved from index 0. So to modify the font bold setting default for the workbook:
private void setWorkbookDefaultFontToBold(Workbook workbook){
Font defaultFont = workbook.getFontAt(0);
defaultFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
}
It's a really obscure piece of information - it's in the POI Sheet Javadoc for setColumnWidth, in the second or so line:
"...can be displayed in a cell that is formatted with the standard font (first font in the workbook)."
I haven't had to use it heavily, so it may have just happened to work for me (the location and non-prevalence of documentation on it makes me slightly leary of recommending depending on it) but it's somewhere you could start looking
private HSSFFont createAndSetFontStyle(HSSFWorkbook wb) {
HSSFFont font = wb.createFont();
font.setFontName(XSSFFont.DEFAULT_FONT_NAME);
font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);
font.setFontHeightInPoints((short)10);
return font;
}
HSSFCellStyle cellStyle = workBook.createCellStyle();
HSSFFont createfont = createAndSetFontStyle(workBook);
cellStyle.setFont(createfont);
cell.setCellStyle(cellStyle);