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();
}
}
Related
i need to change the author name of the generated excel by apache poi in java. Currently the author name of all generated by apache is "Apache POI", i need to change it. can anyone help me on this?
Thanks in advanced.Generated by Apache poi
HSSFWorkbook is a POIDocument which has SummaryInformation.
XSSFWorkbook is a POIXMLDocument which has POIXMLProperties - POIXMLProperties.CoreProperties.
Code to set author (aka creator) for both XSSF and HSSF:
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
class CreateExcelAuthor {
public static void main(String[] args) throws Exception {
String author = "Axel Richter";
Workbook workbook = new XSSFWorkbook();
//Workbook workbook = new HSSFWorkbook();
workbook.createSheet();
if (workbook instanceof XSSFWorkbook) {
((XSSFWorkbook)workbook).getProperties().getCoreProperties().setCreator(author);
} else if (workbook instanceof HSSFWorkbook) {
((HSSFWorkbook)workbook).createInformationProperties();
((HSSFWorkbook)workbook).getSummaryInformation().setAuthor(author);
}
String fileName = (workbook instanceof XSSFWorkbook)?"Excel.xlsx":"Excel.xls";
try (FileOutputStream out = new FileOutputStream(fileName) ) {
workbook.write(out);
}
workbook.close();
}
}
Someone knows why XSSFSheets doesn't provide a method to get its password like the HSSFSheet does with http://javadox.com/org.apache.poi/poi/3.13/org/apache/poi/hssf/usermodel/HSSFSheet.html#getPassword()
The question is why would you need that unsafe short two bytes "password hash"?
But:
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
public class ExcelHSSFXSSFProtectedSheetPassword {
public static void main(String[] args) throws Exception {
Workbook hssfworkbook = new HSSFWorkbook();
Sheet sheet = hssfworkbook.createSheet();
sheet.protectSheet("passwordExcel");
short pwdHash = ((HSSFSheet)sheet).getPassword();
System.out.println(pwdHash);
hssfworkbook.close();
Workbook xssfworkbook = new XSSFWorkbook();
sheet = xssfworkbook.createSheet();
sheet.protectSheet("passwordExcel");
byte[] pwdBytes = ((XSSFSheet)sheet).getCTWorksheet().getSheetProtection().getPassword();
pwdHash = java.nio.ByteBuffer.wrap(pwdBytes).order(java.nio.ByteOrder.BIG_ENDIAN).getShort();
System.out.println(pwdHash);
xssfworkbook.close();
}
}
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..
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) {
}
}
}
I am trying to read data from excel sheet to automate my testing(with a number of login credentials). I am using a utility that I found on web. But it is not running successfully.
Here is the utility
package google;
import java.io.File;
import java.io.IOException;
import java.util.Hashtable;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
public class class2 {
static Sheet wrksheet;
static Workbook wrkbook =null;
static Hashtable dict= new Hashtable();
//Create a Constructor
public class2(String ExcelSheetPath) throws BiffException, IOException
{
//Initialize
wrkbook = Workbook.getWorkbook(new File(ExcelSheetPath));
//For Demo purpose the excel sheet path is hardcoded, but not recommended :)
wrksheet = wrkbook.getSheet("Sheet1");
}
//Returns the Number of Rows
public static int RowCount()
{
return wrksheet.getRows();
`enter code here` }
//Returns the Cell value by taking row and Column values as argument
public static String ReadCell(int column,int row)
{
return wrksheet.getCell(column,row).getContents();
}
//Create Column Dictionary to hold all the Column Names
public static void ColumnDictionary()
{`enter code here`
//Iterate through all the columns in the Excel sheet and store the value
for(int col=0; col <= wrksheet.getColumns();col++)
{
dict.put(ReadCell(col,0), col);
}
}
//Read Column Names
public static int GetCell(String colName)
{
try {
int value;
value = ((Integer) dict.get(colName)).intValue();
return value;
} catch (NullPointerException e) {
return (0);
}
}
}
And following is the class that calls this utility.
package google;
import java.io.IOException;
import jxl.read.biff.BiffException;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import google.class2;
public class class3 {
//Global initialization of Variables
static class2 xlsUtil;
WebDriver driver = new InternetExplorerDriver();
//Constructor to initialze Excel for Data source
public class3() throws BiffException, IOException
{
//Let's assume we have only one Excel File which holds all Testcases. Demo !!!
xlsUtil = new class2("C:/Users/admin/workspace/login.xls");
//Load the Excel Sheet Col in to Dictionary for Further use in our Test cases.
xlsUtil.ColumnDictionary();
}
#BeforeTest
public void EnvironmentalSetup()
{
System.setProperty("webdriver.chrome.driver",
"C:/Users/admin/Downloads/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://192.168.1.20/dental/userlogin");
}
#Test
public void GmailLoginPage() throws InterruptedException {
//Create a for loop.. for iterate through our Excel sheet for all the test cases.
for(int rowCnt = 1;rowCnt <= xlsUtil.RowCount();rowCnt++)
{
//Enter User Name by reading data from Excel
WebElement userName = driver.findElement(By.name("UserName"));
userName.clear();
userName.sendKeys(xlsUtil.ReadCell(xlsUtil.GetCell("EmailUserName"), rowCnt));
//Enter Password
WebElement password = driver.findElement(By.name("Password"));
password.clear();
password.sendKeys(xlsUtil.ReadCell(xlsUtil.GetCell("Emailpassword"), rowCnt));
//Click on the Sign In Button
// WebElement signin = driver.findElement(By.name("signIn"));
password.submit();
//Sleep for some time,so that we can see things in action # Screen :)
Thread.sleep(2000);
}
}
}
But when I run dis cass it says 'cant instantiate google.class3
I don't get the mistake here.
Please help me run this code successfully.
FileInputStream file = newFileInputStream(newFile("C:/Users/admin/workspace/login.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();
if(cell.getColumnIndex() == 0){
driver.findElement(By.name("UserName")).sendKeys(cell.getStringCellValue());
}
else
driver.findElement(By.name("Password")).sendKeys(cell.getStringCellValue());
}
public String getExcelData(String sheetName , int rowNum , int colNum) throws InvalidFormatException, IOException{
FileInputStream fis = new FileInputStream(filePath);
Workbook wb = WorkbookFactory.create(fis);
Sheet sh = wb.getSheet(sheetName);
Row row = sh.getRow(rowNum);
String data = row.getCell(colNum).getStringCellValue();
return data;
}
public int getRowCount(String sheetName) throws InvalidFormatException, IOException{
FileInputStream fis = new FileInputStream(filePath);
Workbook wb = WorkbookFactory.create(fis);
Sheet sh = wb.getSheet(sheetName);
int rowCount = sh.getLastRowNum()+1;
return rowCount;
}
public void setExcelData(String sheetName,int rowNum,int colNum,String data) throws InvalidFormatException, IOException{
FileInputStream fis = new FileInputStream(filePath);
Workbook wb = WorkbookFactory.create(fis);
Sheet sh = wb.getSheet(sheetName);
Row row = sh.getRow(rowNum);
Cell cel = row.createCell(colNum);
cel.setCellType(cel.CELL_TYPE_STRING);
cel.setCellValue(data);
FileOutputStream fos = new FileOutputStream(filePath);
wb.write(fos);
}
public int getcellCount(String sheetName,int rowNum) throws InvalidFormatException, IOException{
FileInputStream fis = new FileInputStream(filePath);
Workbook wb = WorkbookFactory.create(fis);
Sheet sh = wb.getSheet(sheetName);
Row row = sh.getRow(rowNum);
return row.getLastCellNum();
}
public class ExcelLIb {
public static String filePath;
public String getExcelData(String sheetName , String testID , String columnHeader) throws InvalidFormatException, IOException{
String userDir = System.getProperty("user.dir");
filePath = userDir+"\\testdata\\Test_Data.xlsx";
String data = null;
FileInputStream fis = new FileInputStream(filePath);
Workbook wb = WorkbookFactory.create(fis);
Sheet sh = wb.getSheet(sheetName);
int rowcount =getRowCount(sheetName);
for(int r=0 ; r<rowcount; r++){
Row row = sh.getRow(r);
if(row.getCell(0).getStringCellValue().toLowerCase().equals(testID.toLowerCase())){
int col = row.getLastCellNum();
for(int c=0; c<col ; c++){
if(row.getCell(c).getStringCellValue().toLowerCase().equals(columnHeader.toLowerCase())){
row = sh.getRow(r+1);
data = row.getCell(c).getStringCellValue();
break;
}
}
}
}
return data;
}