Hi I wanted to make a column in my apache poi created excel as number only and I wrote the code by the book. But when the excel is generated it still accepts string values.
private void setTemplateDatavalidationNumeric(Sheet sheet,int columnNo){
CellRangeAddressList addressList = new CellRangeAddressList(1, 20000, columnNo, columnNo);
DVConstraint constraint = DVConstraint.createNumericConstraint(DVConstraint.ValidationType.INTEGER,
DVConstraint.OperatorType.BETWEEN, "1", String.valueOf(Integer.MAX_VALUE));
DataValidation dataValidation = new HSSFDataValidation(addressList, constraint);
sheet.addValidationData(dataValidation);
}
please tell me what is wrong.
Related
I need to create an excel file for upload scenario in jmeter. The excel has 3 columns and number of rows is a dynamic value coming from parameter file.
The row values cannot have same data for different excel. So I am using random string to create data. By hard coding number of rows I am able to create file with below code using apache poi but facing issues to handle dynamic number of rows. Can somebody please provide solution?
Below is the code which is working fine for creating 5 rows.
def path = FileServer.getFileServer().getBaseDir;
def separator = File.separator;
def sourceFileName = "CreateDynamicExcel";
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Billing");
Object[] dataTypes = [
["Column1Header","Column2Header","Column3Header"],
["${__RandomString(10,abcdefghij,)}","${__Random(100000000,199999999,)}","${__RandomString(10,abcdefghijklmnopqrst,)}"],
["${__RandomString(10,abcdefghij,)}","${__Random(100000000,199999999,)}","${__RandomString(10,abcdefghijklmnopqrst,)}"],
["${__RandomString(10,abcdefghij,)}","${__Random(100000000,199999999,)}","${__RandomString(10,abcdefghijklmnopqrst,)}"],
["${__RandomString(10,abcdefghij,)}","${__Random(100000000,199999999,)}","${__RandomString(10,abcdefghijklmnopqrst,)}"]];
int rowNum = 0;
for (Object[] datatype:datatypes)
HSSFRow = sheet.createRow(rowNum++);
int colNum = 0;
for(Object filed:datatype){
HSSFCell cell = row.createCell(colNumn+=);
if(filed.instanceof(String){
cell.setCellValue((String) filed);
}
if(filed.instanceof(Integer){
cell.setCellValue((Integer) filed);
}
}
try{
FileOutputStream out = new FileOutputStream(new File(path+separator+sourceFileName+".xls"));
workbook.write(out);
out.close();
}
catch(FileNotFoundException e){
e.printStacktrace();
}
I don't think you should be inlining JMeter Functions or Variables in Groovy scripts because:
It conflicts with Groovy GString Template Engine syntax
Only first occurrence will be cached and used for subsequent iterations
So you can use the following expressions instead:
org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric(10)
org.apache.commons.lang3.RandomUtils.nextInt(100000000, 199999999)
etc.
In case of any problems - take a look at jmeter.log file, in case of any issues you should find the root cause or at least a clue there
Selenium is incorrectly reading the date as 43095 when I enter 26-12-2017. How to get Selenium to read the correct date?
for (int i=0;i<=TcRow;i++)
{
for (int j=0;j<TcCol;j++)
{
Cell Cell=TcSheet.getRow(i).getCell(j);
}
}
Am I reading the format incorrectly?
TcSheet.getRow(i).getCell(j).setCellType(Cell.CELL_TYPE_STRING);
What changes do I need to do here to make sure they read both the string and the date field?
data[i][j]=TcSheet.getRow(i).getCell(j).getStringCellValue();
}
I also faced the same issue during reading the excel file where I'm fetching date is formatted in dd/mm/yyyy format and selenium fetching wrong value.
For that, I have used DataFormatter. It will returns Excel cell value with format e.g. Date format 15-04-208 in excellent then it will returns date with same format. Look below code that I used in my Framework. Hope it will also work for you.
FileInputStream fis = new FileInputStream("path\\to\\file.xlsx");
XSSFWorkbook workbook = new XSSFWorkbook(fis);
XSSFSheet sheet = workbook.getSheetAt(worksheet);
DataFormatter formatter = new DataFormatter();
Cell cell = sheet.getRow(rowNum).getCell(cellNum);
String cellValue = formatter.formatCellValue(cell);
System.out.println(cellValue);
return cellValue;
Let me know if you have any query.
All:
I am pretty new to Apache POI, I wonder if I want to use the builtin function from excel VBA, how can I do that?
For example:
In VBA, I can write something like:
Dim month as String
month = MonthName( Month( Sheets1.Range("C12") ) )
How can I use that function in Apache POI(I do not wanna give that formula to a cell and evaluate it)?
Thanks,
POI does not provide a VBA engine, so you cannot execute VBA with POI.
But there's a way to implement equivalent code in Java and use it with POI. The link below gives an example of how to do that.
https://poi.apache.org/spreadsheet/user-defined-functions.html
Apache poi cannot interpret VBA but of course it has a formula evaluator. So of course you can evaluate Excel formulas directly in apache poi code.
But the VBA function MonthName is not implemented by default. So either you do getting the date from the cell, what is clearly possible using apache poi. And then, you get the month and the month name out of that date using Java code. This is called first approach in following example.
Or you are using a implemented Excel function. TEXT for example. This is called second approach in following example.
import java.io.FileInputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.ss.formula.WorkbookEvaluator;
import org.apache.poi.ss.formula.eval.*;
public class ExcelEvaluateMonthFunctions{
public static void main(String[] args) throws Exception {
Workbook workbook = WorkbookFactory.create(new FileInputStream("workbook.xlsx"));
Sheet sheet = workbook.getSheet("Sheet2");
java.util.Locale.setDefault(java.util.Locale.US);
//first approach:
String monthname = null;
java.util.Date date = sheet.getRow(11).getCell(2).getDateCellValue(); //Sheet2!C12 must contain a date
java.time.LocalDate localDate = date.toInstant().atZone(java.time.ZoneId.systemDefault()).toLocalDate();
monthname = localDate.getMonth().getDisplayName(java.time.format.TextStyle.FULL, java.util.Locale.getDefault());
System.out.println(monthname);
//second approach:
monthname = null;
CreationHelper helper = workbook.getCreationHelper();
XSSFFormulaEvaluator formulaevaluator = (XSSFFormulaEvaluator)helper.createFormulaEvaluator();
WorkbookEvaluator workbookevaluator = formulaevaluator._getWorkbookEvaluator();
ValueEval valueeval = null;
valueeval = workbookevaluator.evaluate("TEXT(" + sheet.getSheetName() +"!C12, \"MMMM\")", null); //Sheet2!C12 must contain a date
if (valueeval instanceof StringValueEval) {
monthname = ((StringValueEval)valueeval).getStringValue();
}
System.out.println(monthname);
workbook.close();
}
}
I am totally new to aspose. kindly help me to achieve the below requirement.
Requirement:- I am trying to make an application which can process an excel file and based on the excel data application will generate an output file( ppt extension).
Special instruction:- Please make a note I will provide ppt template and that template will have a certain placeholder where data will be inserted from uploaded excel.
Work In Progress:-
I have added both Aspose.Cells and Aspose.Slides dll to my project and wrote below PoC.
private void button1_Click(object sender, EventArgs e){
Workbook wb = new Workbook(#“C:\Users\Nilanjan\Desktop\Incident.xlsx”);
Worksheet ws = wb.Worksheets[0];
Cells cells = ws.Cells;
int col = CellsHelper.ColumnNameToIndex(“N”);
int last_row = ws.Cells.GetLastDataRow(col);
DataTable dt = wb.Worksheets[0].Cells.ExportDataTable(0, 0,
wb.Worksheets[0].Cells.MaxDataRow + 1, wb.Worksheets[0].Cells.MaxDataColumn + 1);
Presentation ps = new Presentation();
ISlide slide=ps.Slides[0];
slide=ps.Slides[1];
ps.Save(#“C:\Users\Nilanjan\Desktop\CocoonIncident1.pptx”,Aspose.Slides.Export.SaveFormat.Pptx );
}
Till now I have tried to upload the excel into my code and after processing it I was able to fill a DataTable with the excel data, now next step is to fill the ppt-template with that DataTable data. Please help me to achieve this functionality or please suggest a suitable workaround. Let me know if ppt template or excel file is required.
#Nilanjan,
I have observed your requirements for adding DataTable to PowerPoint slides. There is no direct way available to add DataTable in PowerPoint slides. You need to access every cell in DataTable and add that in PowerPoint slides by following mechanism supported by PowerPoint or Aspose.Slides. I suggest you to please try using following sample code on your end.
public static void DataTableToSlides()
{
String path = #"C:\Aspose Data\";
System.Data.DataTable table = new System.Data.DataTable();
table.Columns.Add("Term", typeof(string));
table.Columns.Add("Value", typeof(float));
table.Rows.Add(#"Term 16", 1.5);
table.Rows.Add(#"Term 15", 0.7);
table.Rows.Add(#"Term 14", 0.7);
table.Rows.Add(#"Term 13", 0.6);
table.Rows.Add(#"Term 12", 0.6);
Presentation pres = new Presentation();
ISlide slide = pres.Slides[0];
double[] colWidth = { 100, 100 };
double[] rowHeight = { 40};// 40, 40,40,40,40 };//1 row additional to hold the headers
ITable slidesTable = slide.Shapes.AddTable(100, 10, colWidth, rowHeight);
slidesTable[0, 0].TextFrame.Text = table.Columns[0].ColumnName;
slidesTable[1, 0].TextFrame.Text = table.Columns[1].ColumnName;
for (int i=0;i<table.Rows.Count;i++)
{
DataRow row = table.Rows[i];
slidesTable.Rows.AddClone(slidesTable.Rows[0], false);
slidesTable[0, i + 1].TextFrame.Text = row[0].ToString();
slidesTable[1, i + 1].TextFrame.Text = row[1].ToString();
}
pres.Save(path + "Saved.pptx",Aspose.Slides.Export.SaveFormat.Pptx);
}
I am working as Support developer/ Evangelist at Aspose.
Many Thanks.
I've been looking on the web for 30 minutes now and can't find any explanation about that. Here is my problem :
I wrote an application with poi to parse some data from 200 excel files or so and put some of it into a new file. I do some cell evaluation with FormulaEvaluator to know the content of the cells before choosing to keep them or not.
Now, when i test it on a test file with only values in the cells, the program works perfectly but when i use it on my pile of files I get this error :
"could not resolve external workbook name"
Is there any way to ignore external workbook references or set up the environment so that it wont evaluate formula with external references?
Because the ones I need don't contain references...
Thank you
Can you not just catch the error, and skip over that cell?
You're getting the error because you've asked POI to evaluate a the formula in a cell, and that formula refers to a different file. However, you've not told POI where to find the file that's referenced, so it objects.
If you don't care about cells with external references, just catch the exception and move on to the next cell.
If you do care, you'll need to tell POI where to find your files. You do this with the setupEnvironment(String[],Evaluator[]) method - pass it an array of workbook names, and a matching array of evaluators for those workbooks.
In order for POI to be able to evaluate external references, it needs access to the workbooks in question. As these don't necessarily have the same names on your system as in the workbook, you need to give POI a map of external references to open workbooks, through the setupReferencedWorkbooks(java.util.Map<java.lang.String,FormulaEvaluator> workbooks) method.
I have done please see below code that is working fine at my side
public static void writeWithExternalReference(String cellContent, boolean isRowUpdate, boolean isFormula)
{
try
{
File yourFile = new File("E:\\Book1.xlsx");
yourFile.createNewFile();
FileInputStream myxls = null;
myxls = new FileInputStream(yourFile);
XSSFWorkbook workbook = new XSSFWorkbook(myxls);
FormulaEvaluator mainWorkbookEvaluator = workbook.getCreationHelper().createFormulaEvaluator();
XSSFWorkbook workbook1 = new XSSFWorkbook(new File("E:\\elk\\lookup.xlsx"));
// Track the workbook references
Map<String,FormulaEvaluator> workbooks = new HashMap<String, FormulaEvaluator>();
workbooks.put("Book1.xlsx", mainWorkbookEvaluator);
workbooks.put("elk/lookup.xlsx", workbook1.getCreationHelper().createFormulaEvaluator());
workbook2.getCreationHelper().createFormulaEvaluator());
// Attach them
mainWorkbookEvaluator.setupReferencedWorkbooks(workbooks);
XSSFSheet worksheet = workbook.getSheetAt(0);
XSSFRow row = null;
if (isRowUpdate) {
int lastRow = worksheet.getLastRowNum();
row = worksheet.createRow(++lastRow);
}
else {
row = worksheet.getRow(worksheet.getLastRowNum());
}
if (!isFormula) {
Cell cell = row.createCell(row.getLastCellNum()==-1 ? 0 : row.getLastCellNum());
cell.setCellValue(Double.parseDouble(cellContent));
} else {
XSSFCell cell = row.createCell(row.getLastCellNum()==-1 ? 0 : row.getLastCellNum());
System.out.println(cellContent);
cell.setCellFormula(cellContent);
mainWorkbookEvaluator.evaluateInCell(cell);
cell.setCellFormula(cellContent);
// mainWorkbookEvaluator.evaluateInCell(cell);
//System.out.println(cell.getCellFormula() + " = "+cell.getStringCellValue());
}
workbook1.close();
myxls.close();
FileOutputStream output_file =new FileOutputStream(yourFile,false);
//write changes
workbook.write(output_file);
output_file.close();
} catch (Exception e) {
e.printStackTrace();
}
}