I want to add a cell in xlsx workbooks sheet containing the quote prefix, and i am trying to create that sheet using POI library. How do I add this type of cell
I found a reference to this with CTXf.setQuotePrefix(boolean quotePrefix) on maven central, but dont know how to add this to the XSSFCell
I have tried using below code
XSSFCell cell=row.createCell(cellIndex);
CTXfImpl ctxf= new CTXfImpl(XmlObject.Factory.newInstance().schemaType());
ctxf.setQuotePrefix(true);
cell.getCTCell().set(ctxf);
cell.setCellValue(data);
getting exception
Exception in thread "main" java.lang.NullPointerException
at org.openxmlformats.schemas.spreadsheetml.x2006.main.impl.CTXfImpl.setQuotePrefix(Unknown Source)
Can anyone help me with this
The CTXf and also the quotePrefix property is part of the XSSFCellStyle and not the XSSFCell.
So we must create a XSSFCellStyle, set the quotePrefix there and then apply this XSSFCellStyle to the XSSFCell.
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import java.io.FileOutputStream;
import java.io.IOException;
class WriteQuotePrefix {
public static void main(String[] args) {
try {
Workbook wb = new XSSFWorkbook();
CellStyle style = wb.createCellStyle();
((XSSFCellStyle)style).getCoreXf().setQuotePrefix(true);
Sheet sheet = wb.createSheet();
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellStyle(style);
cell.setCellValue("1234");
FileOutputStream fileOut = new FileOutputStream("WriteQuotePrefix.xlsx");
wb.write(fileOut);
fileOut.close();
} catch (IOException ioex) {
}
}
}
Related
lock rename of sheet name POI java
how to protect sheet name to not let users change it
XSSFSheet sheet = ((XSSFSheet)s);
//to lock my sheet name
sheet.lockmysheetName();
I want to protect just sheet name.
Microsoft Excel does not provide lock the sheet name on sheet level. There is a possibility to protect a workbook. That protects the structure of the workbook. This includes the lock of the sheet names but also the lock of the sheets order and the lock inserting new sheets.
This is what XSSFWorkbook.lockStructure sets.
HSSFWorkbook has nothing comparable up to now. But using InternalWorkbook and WorkbookRecordList and knowledge about the binary record stream in a binary *.xls workbook one can achieve the same.
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;
import org.apache.poi.hssf.record.Record;
import org.apache.poi.hssf.record.ProtectRecord;
import org.apache.poi.hssf.model.InternalWorkbook;
import org.apache.poi.hssf.model.WorkbookRecordList;
public class CreateExcelLockStructure {
static void lockStructure(HSSFWorkbook hssfWorkbook) {
InternalWorkbook internalWorkbook = hssfWorkbook.getInternalWorkbook();
WorkbookRecordList workbookRecordList = internalWorkbook.getWorkbookRecordList();
int protpos = workbookRecordList.getProtpos();
Record record = workbookRecordList.get(protpos);
if (record instanceof ProtectRecord) {
ProtectRecord protectRecord = (ProtectRecord)record;
protectRecord.setProtect(true);
} else {
ProtectRecord protectRecord = new ProtectRecord(true);
protpos = workbookRecordList.size() - 1;
workbookRecordList.add(protpos, protectRecord);
workbookRecordList.setProtpos(protpos);
}
}
public static void main(String[] args) throws Exception {
Workbook workbook = new XSSFWorkbook(); String filePath = "./CreateExcelLockStructure.xlsx";
//Workbook workbook = new HSSFWorkbook(); String filePath = "./CreateExcelLockStructure.xls";
Sheet sheet = workbook.createSheet("SheetName1");
sheet = workbook.createSheet("SheetName2");
if (workbook instanceof XSSFWorkbook) {
XSSFWorkbook xssfWorkbook = (XSSFWorkbook)workbook;
xssfWorkbook.lockStructure();
} else if (workbook instanceof HSSFWorkbook) {
HSSFWorkbook hssfWorkbook = (HSSFWorkbook)workbook;
lockStructure(hssfWorkbook);
}
FileOutputStream out = new FileOutputStream(filePath);
workbook.write(out);
out.close();
workbook.close();
}
}
I want to write numbers to Excel in scientific notation. In Apache Poi it is possible to set the number format of a cell like this:
Cell cell = ...
CellStyle style = workbook.createCellStyle();
DataFormat format = workbook.createDataFormat();
style.setDataFormat(format.getFormat("#0.00"));
cell.setCellStyle(style);
But when I use a pattern like "#0.00E0" I get an error from Excel when opening the file and the number format is lost.
Here is a full example:
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class Main {
public static void main(String[] args) {
try (Workbook wb = new XSSFWorkbook();
FileOutputStream fos = new FileOutputStream("out.xlsx")) {
Sheet sheet = wb.createSheet();
Cell cell = sheet.createRow(0).createCell(0);
CellStyle style = wb.createCellStyle();
DataFormat format = wb.createDataFormat();
style.setDataFormat(format.getFormat("#0.00E0"));
cell.setCellStyle(style);
cell.setCellValue(Math.random());
wb.write(fos);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Thanks!
The correct format for scientific notation would be:
format.getFormat("0.00E+00")
I have downloaded Apache Poi Jar but when I write the following code (which a youtube instructor ran with ease), it does not give me any output excel file. What am I doing wrong here? I hover my mouse over HSSFWorkbook eclipse tells me
org.apache.poi.hssf.usermodel.HSSFWorkbook Note: This element neither has attached source nor attached Javadoc and hence no Javadoc could be found.
The code.
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
public class WriteExcel {
public static void main(String[] args) throws FileNotFoundException, IOException {
HSSFWorkbook workbook= new HSSFWorkbook();
HSSFSheet sheet= workbook.createSheet("FirstExcelSheet");
HSSFRow row= sheet.createRow(0);
HSSFCell cell= row.createCell(0);
cell.setCellValue("1,Cell");
workbook.write(new FileOutputStream("excel.xls"));
workbook.close();
workbook.getFirstVisibleTab();
}
}
the first thing use XSSFWorkbook instead of HSSFWorkbook take a look at this link,
and the second thing you have to out stream this file add this line
try (FileOutputStream outputStream = new FileOutputStream("slsx.xlsx")) {
workbook.write(outputStream);
so your code should be like this
public static void main(String[] args) throws Exception {
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet spreadsheet = workbook.createSheet("sheet1");
XSSFRow row = spreadsheet.createRow(1);
XSSFCell cell = row.createCell(1);
cell.setCellValue("test");
try (FileOutputStream out = new FileOutputStream(new File("Writesheet.xlsx"))) {
workbook.write(out);
}
System.out.println("Writesheet.xlsx written successfully");
}
you should add your path in this line like:
workbook.write(new FileOutputStream("{yourpath}/excel.xls"));
it works..
There is a excel file which is having lot of file names in one of its column . I need to write a java code that should read those file names and generate the same in destination.Can any one help me ?
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class Test {
public static void main(String[] args) throws IOException {
try {
FileInputStream file = new FileInputStream(new File("C:\\test.xls"));
HSSFWorkbook workbook = new HSSFWorkbook(file);
HSSFSheet sheet = workbook.getSheetAt(0);
//Iterate through each rows from first sheet
Iterator<Row> rowIterator = sheet.iterator();
while(rowIterator.hasNext()) {
Row row = rowIterator.next();
//For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
while(cellIterator.hasNext()) {
Cell cell = cellIterator.next();
System.out.print(cell.getStringCellValue() + "\t\t");
FileOutputStream outFile =new FileOutputStream(new File("C:\\"+cell.getStringCellValue()));
workbook.write(outFile);
}
System.out.println("");
}
file.close();
/* FileOutputStream outFile =new FileOutputStream(new File("C:\\update.xls"));
workbook.write(outFile);*/
//outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
There are some libraries you can use to read excel files. In my case, I chose the Apache POI which you can download for free and then add to your project. Once you added it, create your Document:
HSSFWorkbook workbook = new HSSFWorkbook( new FileInputStream("filename.xls") );
or, if it's an excel document from 2007 or later:
XSSFWorkbook workbook = new XSSFWorkbook( new FileInputStream("filename.xlsx") );
Now you can iterate through each row and read out the first column:
for( Row row : workbook.getSheetAt(0) ) // Go through each row in sheet 0
System.out.println( row.getCell(0).getStringCellValue() );
public class Test {
public static void main(String[] args) throws IOException {
try {
FileInputStream file = new FileInputStream(new File("D:\\sampleFileNames.xls"));
HSSFWorkbook workbook = new HSSFWorkbook(file);
FileOutputStream outFile= null;
HSSFSheet sheet = workbook.getSheetAt(0);
//Iterate through each rows from first sheet
Iterator<Row> rowIterator = sheet.iterator();
while(rowIterator.hasNext()) {
Row row = rowIterator.next();
//For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
Cell cell = cellIterator.next();
File file1 = new File("D:\\Ganesh\\"+cell.getStringCellValue().toString());
if(!file1.createNewFile()) {
System.out.println("File already exists");
/* Cell cell = cellIterator.next();
System.out.print(cell.getStringCellValue() + "\t\t");
outFile =new FileOutputStream(new File("D:\\Ganesh\\"+cell.getStringCellValue().toString()));
//workbook.write(outFile);
System.out.println("");
}
file.close();
outFile.close();
/* FileOutputStream outFile =new FileOutputStream(new File("C:\\update.xls"));
workbook.write(outFile);*/
//outFile.close();
}
}
}catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Emp ID Name Salary
1.0 john 2000000.0
2.0 dean 4200000.0
3.0 sam 2800000.0
4.0 cass 600000.0
I have created this code:
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
public class sample2
{
public static void main(String[] args) {
new sample2().sample2();
}
}
FileInputStream file = new FileInputStream(new File("C:\\test.xls"));
//Get the workbook instance for XLS file
HSSFWorkbook workbook = new HSSFWorkbook(test);
//Get first sheet from the workbook
HSSFSheet sheet = workbook.getSheetAt(0);
//Get iterator to all the rows in current sheet
Iterator<Row> rowIterator = sheet.iterator();
//Get iterator to all cells of current row
Iterator<Cell> cellIterator = row.cellIterator();
try {
FileInputStream file = new FileInputStream(new File("C:\\test.xls"));
//Get the workbook instance for XLS file
HSSFWorkbook workbook = new HSSFWorkbook(file);
//Get first sheet from the workbook
HSSFSheet sheet = workbook.getSheetAt(0);
//Iterate through each rows from first sheet
Iterator<Row> rowIterator = sheet.iterator();
while(rowIterator.hasNext()) {
Row row = rowIterator.next();
//For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
while(cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch(cell.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
System.out.print(cell.getBooleanCellValue() + "\t\t");
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t\t");
break;
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + "\t\t");
break;
}
}
System.out.println("");
}
file.close();
FileOutputStream out =
new FileOutputStream(new File("C:\\test.xls"));
workbook.write(out);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
for reading the content from this excel file using POI library. My editor is Eclipse. But when i run the program I took this: Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method sample2() is undefined for the type sample2
at sample2.main(sample2.java:17)
Any help?
Thank u in advance!
public class sample2
{
public static void main(String[] args) {
new sample2().sample2(); // This is wrong too.
}
}
All your code after this is pointless. Your class has basically ended with the second }.
You might want to move all that within your main() method.
Also, this piece of code in the main() method new sample2().sample2(); is wrong.
It should be like this
sample2 s = new sample2();
Delete the last curly brace in your code :
{
public static void main(String[] args) {
new sample2().sample2();
}
}
And then creat a method named test2() like this:
public void sample2(){ //Put your code here }