I wanted to set font of the title row in a spreadsheet bold. I was able to do that in my main function with the following code:
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet dataSheet = workbook.createSheet("Data");
HSSFCellStyle fontStyle = workbook.createCellStyle();
HSSFFont font = workbook.createFont();
font.setBold(true);
fontStyle.setFont(font);
Row row = dataSheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellStyle(fontStyle);
cell.setCellValue("ID");
Since createCellStyle is method of HSSFWorkbook, if I write to the sheet by calling a function which takes the sheet but not the workbook as parameter, how do I set the cell style?
public class SummaryXlsCreator {
public static void main(String[] args) {
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet dataSheet = workbook.createSheet("Data");
writeCDMarker(dataSheet);
}
public static void writeCDMarker(HSSFSheet sheet) {
int rownum = 0;
int cellnum = 0;
Row row = sheet.createRow(rownum++);
Cell cell = row.createCell(cellnum++);
// write first row of sheet "Data"
cell.setCellValue("ID");
}
Use getWorkbook() to get the parent and proceed with the existing code.
sheet.getWorkbbok().createCellStyle();
https://poi.apache.org/apidocs/org/apache/poi/hssf/usermodel/HSSFSheet.html
You can use the static CellUtil.setCellStyleProperties(Cell cell, Map<String, Object> properties) to format your cell without needing a reference to your workbook or sheet.
Example usage:
// Format cell into date time format with "m/d/yy h:mm",
// which is converted to user's locale in Excel.
CellUtil.setCellStyleProperties(cell, Collections.singletonMap(CellUtil.DATA_FORMAT, (short) 22));
Related
HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
HSSFSheet hssfSheet = hssfWorkbook.createSheet();
HSSFRow hssfRow = hssfSheet.createRow(0);
HSSFCell hssfCell = hssfRow.createCell(i);
hssfCell.setCellValue(name.getText().toString());
i want to store previous hssf cell value in excel , when i enter new cell value it does,nt store previous hssf cell value...
I have a java code that retrieves the data from the database and copies them to an excel sheet then creates a file,
but all the retrieval data are shown in 1 sheet my problem is to separate them into separated sheets regarding the date, please find my code and advise
List<Excelvo> excelvos = null;
String strDate = "28-02-2021";
String strToDate = "28-03-2021";
Workbook workbook = new XSSFWorkbook();
try {
excelvos = ExcelDao.getInstance().getShabanCodes(100, strDate, strToDate);
} catch (Exception ex) {
Logger.getLogger(CopyToExcel.class.getName()).log(Level.SEVERE, null, ex);
}
// Workbook workbook = new XSSFWorkbook(); // new HSSFWorkbook() for generating `.xls` file
//System.out.println(strDate.substring(0, 5));
/* CreationHelper helps us create instances of various things like DataFormat,
Hyperlink, RichTextString etc, in a format (HSSF, XSSF) independent way */
CreationHelper createHelper = workbook.getCreationHelper();
// Create a Sheet
// for loop to create more than 1 sheet
Sheet sheet = workbook.createSheet(strDate.substring(0, 5));
// Create a Font for styling header cells
Font headerFont = workbook.createFont();
headerFont.setFontHeightInPoints(
(short) 12);
headerFont.setColor(IndexedColors.BLACK.getIndex());
// Create a CellStyle with the font
CellStyle headerCellStyle = workbook.createCellStyle();
headerCellStyle.setFont(headerFont);
headerFont.setBoldweight(headerFont.BOLDWEIGHT_BOLD);
headerCellStyle.setFillBackgroundColor(IndexedColors.GREY_50_PERCENT.getIndex());
headerCellStyle.setAlignment(headerCellStyle.ALIGN_CENTER);
// Create a Row
Row headerRow = sheet.createRow(0);
// Create cells
//for the table header.
for (int i = 0;
i < columns.length;
i++) {
Cell cell = headerRow.createCell(i);
cell.setCellValue(columns[i]);
cell.setCellStyle(headerCellStyle);
}
// Create Cell Style for formatting Date
CellStyle dateCellStyle = workbook.createCellStyle();
dateCellStyle.setDataFormat(createHelper.createDataFormat().getFormat("dd-MM-yyyy HH:mm:ss"));
dateCellStyle.setBorderBottom(HSSFCellStyle.BORDER_MEDIUM);
dateCellStyle.setBorderLeft(HSSFCellStyle.BORDER_MEDIUM);
dateCellStyle.setBorderRight(HSSFCellStyle.BORDER_MEDIUM);
dateCellStyle.setBorderTop(HSSFCellStyle.BORDER_MEDIUM);
headerCellStyle.setAlignment(headerCellStyle.ALIGN_CENTER);
dateCellStyle.setBorderBottom(CellStyle.BORDER_THIN);
dateCellStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());
dateCellStyle.setBorderLeft(CellStyle.BORDER_THIN);
dateCellStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());
dateCellStyle.setBorderRight(CellStyle.BORDER_THIN);
dateCellStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());
dateCellStyle.setBorderTop(CellStyle.BORDER_THIN);
dateCellStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());
// Create Other rows and cells with employees data
int rowNum = 1;
for (Excelvo excelvo
: excelvos) {
Row row = sheet.createRow(rowNum++);
row.createCell(0)
.setCellValue(excelvo.getCode());
row.createCell(1)
.setCellValue(excelvo.getSentDate());
row.createCell(2)
.setCellValue(excelvo.getCampaign());
row.createCell(3)
.setCellValue(excelvo.getMsisdn());
}
// Resize all columns to fit the content size
for (int i = 0;
i < columns.length;
i++) {
sheet.autoSizeColumn(i);
}
//String excelFilePath = "D:/Excel/MyFirstExcel.xlsx";
//FileInputStream inputStream = new FileInputStream(new File(excelFilePath));
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("sugar sha3ban campaign 2021 code log 28 Feb - 30 Mar.xlsx");
workbook.write(fileOut);
fileOut.close();
I need to separate the data into multiple sheets regarding the date
the retrieved data: each month has data I want to separate this data to put each month with their data in a sheet?
By using MemPOI you can simply execute different queries and bind them to different sheets, letting the db to apply the required filters. MemPOI will take care of the generation. Something like this:
MempoiSheet januarySheet = MempoiSheetBuilder.aMempoiSheet()
.withSheetName("January")
.withPrepStmt(conn.prepareStatement("SELECT * FROM MyTable WHERE date = 'mydate'"))
.build();
MempoiSheet februarySheet = MempoiSheetBuilder.aMempoiSheet()
.withSheetName("February")
.withPrepStmt(conn.prepareStatement("SELECT * FROM MyTable WHERE date = 'mydate 2'"))
.build();
MemPOI memPOI = MempoiBuilder.aMemPOI()
.withAdjustColumnWidth(true)
.addMempoiSheet(januarySheet)
.addMempoiSheet(februarySheet)
.build();
Hey all I am trying to get my cell to vertical line instead of just being aligned by the left side using POI.
This is my java code:
static CellStyle headerCellStyle = workbook.createCellStyle();
headerCellStyle = workbook.createCellStyle();
Row headerRow = null;
sheet = workbook.createSheet("String " + sheetname);
headerCellStyle.setWrapText(true);
headerCellStyle.setAlignment(HorizontalAlignment.LEFT);
headerCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
headerCellStyle.setVerticalAlignment(VerticalAlignment.MIDDLE);
// Create a Row
headerRow = sheet.createRow(0);
However, the line headerCellStyle.setVerticalAlignment(VerticalAlignment.MIDDLE); has an error of:
The method setVerticalAlignment(org.apache.poi.ss.usermodel.VerticalAlignment) in the type CellStyle is not applicable for the arguments (org.apache.poi.sl.usermodel.VerticalAlignment)
How can i go about getting this to work if I have already defined it as an static CellStyle headerCellStyle = workbook.createCellStyle();?
Changing to SS does not seem to have the "middle" option?
This is the difference within excel for those 2 types:
The default way:
The Middle way (the way I am wanting):
The Center way:
Your second image (the way you want) shows CellStyle.setVerticalAlignment(VerticalAlignment.CENTER). Your third image shows CellStyle.setAlignment(HorizontalAlignment.CENTER).
There is a difference between setVerticalAlignment(VerticalAlignment.CENTER) and setAlignment(HorizontalAlignment.CENTER). The first sets vertical alignment to center (aka middle). The second sets horizontal alignment to center.
Complete Example:
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
class CreateExcelVerticalAlignment {
public static void main(String[] args) throws Exception {
// try (Workbook workbook = new XSSFWorkbook();
// FileOutputStream fileout = new FileOutputStream("Excel.xlsx") ) {
try (Workbook workbook = new HSSFWorkbook();
FileOutputStream fileout = new FileOutputStream("Excel.xls") ) {
CellStyle headerCellStyle = workbook.createCellStyle();
headerCellStyle = workbook.createCellStyle();
headerCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
Sheet sheet = workbook.createSheet();
sheet.setColumnWidth(0, 20*256);
Row row = sheet.createRow(0);
row.setHeightInPoints(40);
Cell cell = row.createCell(0);
cell.setCellStyle(headerCellStyle);
cell.setCellValue("1082192560 1868");
workbook.write(fileout);
}
}
}
Result:
I am trying to read column values from excel file which looks like this
This is my code for reading excel file
Xls_Reader d = new Xls_Reader("C:\\TestData.xlsx");
System.out.println(d.getRowCount("sheetname"));
String s1 = String.valueOf(d.getCellData("TC03", "Contract_ID",3));
s1 =(int)Double.parseDouble(s1) + "";
System.out.println(s1);
in this code i am able to get record of one row. But i need to print all the Row value.
Please suggest.
What Jars you are using for this approach?
I have following code to read data from excel using apache poi -
public static void main(String args[]) throws IOException
{
FileInputStream fis = new FileInputStream(new File("your_file.xlsx"));
XSSFWorkbook workbook = new XSSFWorkbook(fis); // XSSFWorkbook for .xlsx file
XSSFSheet sheet = workbook.getSheetAt(0); // open sheet 1
Iterator<Row> rowIterator = sheet.iterator();
// Traversing over each row of XLSX file
while (rowIterator.hasNext())
{
Row row = rowIterator.next();
if(row.getRowNum()!=0) // skip title row
{
Iterator cellIterator = row.cellIterator();
while (cellIterator.hasNext())
{
Cell cell = (Cell) cellIterator.next();
System.out.print(cell.getStringCellValue() + "\t");
}
}
}
}
Note :- In my case cell in excel sheet formatted as text you can change cell.getStringCellValue() method as per your data.
This method will be print all sheet of your excel document:
public static void GetEmail() throws IOException{
InputStream in = new FileInputStream("C:/path to your doc");
HSSFWorkbook wb = new HSSFWorkbook(in);
ExcelExtractor extractor = new ExcelExtractor(wb);
extractor.setFormulasNotResults(false); // Read formulas
extractor.setIncludeSheetNames(false);
String text = extractor.getText();
System.out.println(text);
}
I have new hand on Android. I have made a report using ListView which is divided into three columns named DateTime, OnOffStatus, AlarmImage.
It work fine and looks good enough but now I want to export this table data to Excel format. Is it possible or not and how?
thanks in advance
Om Parkash Kaushik
Start of by looking at http://poi.apache.org/ and http://poi.apache.org/spreadsheet/index.html
I use this library to all of my excel reports.
Start of by creating a Workbook:
HSSFWorkbook workbook = new HSSFWorkbook();
Map<String, CellStyle> styles = createStyles(workbook);
HSSFSheet sheet = workbook.createSheet();
Setup some style:
private static Map<String, CellStyle> createStyles(Workbook wb) {
Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
CellStyle style;
Font monthFont = wb.createFont();
monthFont.setFontHeightInPoints((short) 11);
monthFont.setColor(IndexedColors.WHITE.getIndex());
style = wb.createCellStyle();
style.setAlignment(CellStyle.ALIGN_CENTER);
style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex());
style.setFillPattern(CellStyle.SOLID_FOREGROUND);
style.setFont(monthFont);
style.setWrapText(true);
styles.put("header", style);
style = wb.createCellStyle();
style.setAlignment(CellStyle.ALIGN_CENTER);
style.setWrapText(true);
style.setBorderRight(CellStyle.BORDER_NONE);
style.setBorderLeft(CellStyle.BORDER_NONE);
style.setBorderTop(CellStyle.BORDER_NONE);
style.setBorderBottom(CellStyle.BORDER_NONE);
styles.put("cell", style);
return styles;
}
Then setup a header row:
private static final String[] article_headers = {"header1", "header2"};
// Header row
Row headerRow = sheet.createRow(0);
headerRow.setHeightInPoints(40);
Cell headerCell;
for (int i = 0; i < article_headers.length; i++) {
headerCell = headerRow.createCell(i);
headerCell.setCellValue(article_headers[i]);
headerCell.setCellStyle(styles.get("header"));
}
And then you continue with the rows by setting their style and value.
Hope this helps and if you find this helpful, remember to accept.
// Jakob