I am having the Excel Sheet
UserName Password
Rahul test123$
Manish Password
test newpwd
So when i pass value "test" i should get the "newpwd" as output.
Can you please help me.
you may use "jxl" library of java .
try this:
package com.quicklyjava;
import jxl.*;
import jxl.read.biff.BiffException;
import java.io.File;
import java.io.IOException;
public class JavaExcelRead {
public static void main(String[] args) {
try {
//Create a workbook object from the file at specified location.
//Change the path of the file as per the location on your computer.
Workbook wrk1 = Workbook.getWorkbook(new File("C:/test.xls"));
//Obtain the reference to the first sheet in the workbook
Sheet sheet1 = wrk1.getSheet(0);
//Obtain reference to the Cell using getCell(int col, int row) method of sheet
Cell colArow1 = sheet1.getCell(0, 0);
Cell colBrow1 = sheet1.getCell(1, 0);
Cell colArow2 = sheet1.getCell(0, 1);
//Read the contents of the Cell using getContents() method, which will return
//it as a String
String str_colArow1 = colArow1.getContents();
String str_colBrow1 = colBrow1.getContents();
String str_colArow2 = colArow2.getContents();
//Display the cell contents
System.out.println("Contents of cell Col A Row 1: \""+str_colArow1 + "\"");
System.out.println("Contents of cell Col B Row 1: \""+str_colBrow1 + "\"");
System.out.println("Contents of cell Col A <span class="IL_AD" id="IL_AD12">Row 2</span>: \""+str_colArow2 + "\"");
} catch (BiffException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Related
I am trying to fetch the data from the Numbers application in macOS, In below code is not able to fetch the value from the cell.
public class Excel {
public static String getdata(String sheetname, int rowvalue, int cellvalue)
{
String value = "";
try {
FileInputStream fis = new FileInputStream("./Excel/Logincred.xlsx");
Workbook wb = WorkbookFactory.create(fis);
Sheet sh = wb.getSheet(sheetname);
Row r = sh.getRow(rowvalue);
Cell c = r.getCell(cellvalue);
value = c.toString();
}
catch(Exception e)
{
}
return value;
}
}
You need to append ' before each number in your excel sheet and then your code would work completely fine.
So lets say, you have a value 4 in your excel, you need to change it to '4 and then your read from excel would work
I want to add a new column to my pivot table with the value field setting as "show as % of grand total".
This is output I am getting:
Row Labels Sum
Jane 20
Tarzan 5
Terk 10
Grand Total 35
This is the expected output:
Row Labels Sum
Jane 57.14%
Tarzan 14.29%
Terk 28.57%
Grand Total 100.00%
this is the code : by default we use DataConsolidateFunction.SUM, but I want to show data as % of Grand total by using POI ,like we can do in excel
import java.io.*;
import java.util.Iterator;
import java.util.List;
import org.apache.*;
import org.apache.poi.ss.SpreadsheetVersion;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DataConsolidateFunction;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.util.AreaReference;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.xssf.usermodel.XSSFPivotTable;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPivotField;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTPivotFields;
public class App
{
public static void main( String[] args )
{
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet1 = wb.createSheet("1e");
XSSFSheet sheet = wb.createSheet("1econtent");
setCellData(sheet,wb);
wb.getSheet("1econtent").setSelected(false);
AreaReference source = new AreaReference("A1:D5");
CellReference position = new CellReference(8,0);
XSSFPivotTable pivotTable = sheet1.createPivotTable(source, position,wb.getSheet("1econtent"));
pivotTable.addRowLabel(0);
pivotTable.addRowLabel(3);
pivotTable.addColumnLabel(DataConsolidateFunction.SUM, 1);
try (FileOutputStream fileOut = new FileOutputStream("ooxml-pivottablesa.xlsx")) {
wb.write(fileOut);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void setCellData(XSSFSheet sheet,XSSFWorkbook wb){
Row row1 = sheet.createRow(0);
// Create a cell and put a value in it.
Cell cell11 = row1.createCell(0);
cell11.setCellValue("Names");
Cell cell12 = row1.createCell(1);
cell12.setCellValue("Confinements");
Cell cell13 = row1.createCell(2);
cell13.setCellValue("ConfinementsAS");
Cell cell14 = row1.createCell(3);
cell14.setCellValue("Human");
Row row2 = sheet.createRow(1);
Cell cell21 = row2.createCell(0);
cell21.setCellValue("Jane");
Cell cell22 = row2.createCell(1);
cell22.setCellValue(10);
Cell cell23 = row2.createCell(2);
cell23.setCellValue(100);
Cell cell24 = row2.createCell(3);
cell24.setCellValue("Yes");
Row row3 = sheet.createRow(2);
Cell cell31 = row3.createCell(0);
cell31.setCellValue("Tarzan");
Cell cell32 = row3.createCell(1);
cell32.setCellValue(5);
Cell cell33 = row3.createCell(2);
cell33.setCellValue(90);
Cell cell34 = row3.createCell(3);
cell34.setCellValue("Yes");
Row row4 = sheet.createRow(3);
Cell cell41 = row4.createCell(0);
cell41.setCellValue("Terk");
Cell cell42 = row4.createCell(1);
cell42.setCellValue(10);
Cell cell43 = row4.createCell(2);
cell43.setCellValue(90);
Cell cell44 = row4.createCell(3);
cell44.setCellValue("No");
cell44.getCellStyle().setHidden(true);
Row row5 = sheet.createRow(4);
Cell cell211 = row5.createCell(0);
cell211.setCellValue("Jane");
Cell cell221 = row5.createCell(1);
cell221.setCellValue(10);
Cell cell231 = row5.createCell(2);
cell231.setCellValue(60);
Cell cell241 = row5.createCell(3);
cell241.setCellValue("No");
cell241.getCellStyle().setHidden(true);
}
}
The feature to show the values as percent of column total is not yet implemented in XSSFPivotTable. But we can set it using the low level underlying CT*-classes of ooxml-schemas.
Example:
...
pivotTable.addColumnLabel(DataConsolidateFunction.SUM, 1);
pivotTable.getCTPivotTableDefinition().getDataFields().getDataFieldArray(0).setShowDataAs(
org.openxmlformats.schemas.spreadsheetml.x2006.main.STShowDataAs.PERCENT_OF_COL);
DataFormat dataformat = wb.createDataFormat();
short numFmtId = dataformat.getFormat("0.00%");
pivotTable.getCTPivotTableDefinition().getDataFields().getDataFieldArray(0).setNumFmtId(numFmtId);
...
For the CellRange we can pass -1 for both the start/end row parameters to apply styles and dataValidators to the entire column.
But how to skip the header?
The ideal solution would be a CellRangeAddressList created with "A1:A$", but it only have int constructors.
i tried assuming that -1 is a special value that means something special, but CellRangeAddressList(1, -1, ...) fails with a "start row > finish row" error. Then I also tried assuming -1 meant last cell, but going from last to 1 CellRangeAddressList(-1, 1, ...) resulted in no cell selected.
Lastly I tried to remove the first row from the CellRangeAddressList(-1, -1, ...) but it is not possible to manipulate the ranges after creation as far as I could tell from the docs.
Creating a CellRangeAddress for whole column except first row means a CellRangeAddress starts on row 2 and goes up to maximum rows count. This depends on SpreadsheetVersion. In EXCEL2007 the maximum rows count is 2^20 = 1048576. In EXCEL97 the maximum rows count is 2^16 = 65536.
Using SpreadsheetVersion we can get that different maximum rows count dependent on SpreadsheetVersion.
Example:
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.ss.SpreadsheetVersion;
class CreateCellRangeAddressList {
public static void main(String[] args) throws Exception {
//Workbook workbook = new XSSFWorkbook();
Workbook workbook = new HSSFWorkbook();
// ...
int lastRow = workbook.getSpreadsheetVersion().getLastRowIndex();
CellRangeAddressList cellRangeAddressList = new CellRangeAddressList(
1, // row 2
lastRow,
2, // column C
2);
System.out.println(cellRangeAddressList.getCellRangeAddress(0));
//C2:C1048576 or C2:C65536 dependent on SpreadsheetVersion
// ...
}
}
Because the question was about data validation for whole column except first row let's have a example for this.
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.ss.util.CellRangeAddressList;
class CreateExcelDataValidationListsWholeColumn {
public static void main(String[] args) throws Exception {
//Workbook workbook = new HSSFWorkbook();
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Sheet1");
sheet.createRow(0).createCell(1).setCellValue("col2Head");
//data validation in column B, except first row:
DataValidationHelper dvHelper = sheet.getDataValidationHelper();
DataValidationConstraint dvConstraint = dvHelper.createExplicitListConstraint(new String[]{"X", "Y"}) ;
int lastRow = workbook.getSpreadsheetVersion().getLastRowIndex();
CellRangeAddressList addressList = new CellRangeAddressList(1, lastRow, 1, 1); //B2:B1048576
DataValidation validation = dvHelper.createValidation(dvConstraint, addressList);
sheet.addValidationData(validation); // data validation for B2:B1048576
FileOutputStream out = null;
if (workbook instanceof HSSFWorkbook) {
out = new FileOutputStream("CreateExcelDataValidationListsWholeColumn.xls");
} else if (workbook instanceof XSSFWorkbook) {
out = new FileOutputStream("CreateExcelDataValidationListsWholeColumn.xlsx");
}
workbook.write(out);
workbook.close();
out.close();
}
}
This results in sheet XML as follows:
<worksheet>
<dimension ref="B1"/>
<sheetViews>
<sheetView workbookViewId="0" tabSelected="true"/>
</sheetViews>
<sheetFormatPr defaultRowHeight="15.0"/>
<sheetData>
<row r="1"><c r="B1" t="s"><v>0</v></c></row>
</sheetData>
<dataValidations count="1">
<dataValidation type="list" sqref="B2:B1048576" allowBlank="true" errorStyle="stop">
<formula1>"X,Y"</formula1>
</dataValidation>
</dataValidations>
<pageMargins bottom="0.75" footer="0.3" header="0.3" left="0.7" right="0.7" top="0.75"/>
</worksheet>
And using HSSFWorkbook the resulting CreateExcelDataValidationListsWholeColumn.xls is 4 KByte in size.
i used apache poi to rewrite a CSV file to Excel, for any string like HH:mm:ss, i need to convert it to the appropriate Excel data type so that user can apply sum() function on that column. i tried different datatype, but when i open the excel file i cannot sum that column the sum always showed as "0:00:00", even though clicking on that column in excel it showed as 'Time' data type,
here is my code:
CreationHelper creationHelper = workbook.getCreationHelper();
HSSFCellStyle timeStyle = workbook.createCellStyle();
timeStyle.setDataFormat(creationHelper.createDataFormat().getFormat("h:mm:ss"));
cell.setCellValue(column);
if (isTime(column)) {
cell.setCellStyle(timeStyle);
}
private boolean isTime(String value) {
try {
dtf.parseDateTime(value);
return true;
} catch (IllegalArgumentException e) {
return false;
}
}
and here is my excel file
If the object column in your code is String, then the content of the cell will always be string (text) cell content after cell.setCellValue(column). This content the function SUM cannot work with. Those functions needs numeric content. In Excel date and time also is numeric content only formatted as date-time. With default settings 1 = 1 day = 01/01/1900 00:00:00. 1 hour = 1/24, 1 minute = 1/24/60, 1 second = 1/24/60/60.
If column is string of format "HH:MM:SS", then DateUtil.convertTime can be used to convert this string into a Excel valuable time.
Complete example which shows what not works and what works:
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.ss.usermodel.DateUtil;
public class ExcelCalculateTimeValues {
public static void main(String[] args) throws Exception {
Workbook workbook = new HSSFWorkbook();
//Workbook workbook = new XSSFWorkbook();
CreationHelper createHelper = workbook.getCreationHelper();
CellStyle styletime = workbook.createCellStyle();
styletime.setDataFormat(createHelper.createDataFormat().getFormat("hh:mm:ss"));
Sheet sheet = workbook.createSheet();
sheet.createRow(0).createCell(0).setCellValue("Time sting");
sheet.getRow(0).createCell(1).setCellValue("Time");
String[][] tableData = new String[][]{
{"12:34:00", "22:45:00"},
{"23:45:05", "01:34:40"},
{"08:01:00", "13:23:00"},
{"15:41:12", "23:23:22"}
};
int r = 1;
for (String[] rowData : tableData) {
Row row = sheet.createRow(r++);
int c = 0;
for (String cellData : rowData) {
Cell cell = row.createCell(c);
if (c == 0 ) {
cell.setCellValue(cellData); //this sets string cell data
} else if (c == 1) {
cell.setCellValue(DateUtil.convertTime(cellData)); //this sets datetime cell data
}
cell.setCellStyle(styletime);
c++;
}
}
sheet.createRow(r).createCell(0).setCellFormula("SUM(A2:A"+r+")"); //cannot work because of string values in A2:A4
sheet.getRow(r).createCell(1).setCellFormula("SUM(B2:B"+r+")"); //will work
workbook.setForceFormulaRecalculation(true);
if (workbook instanceof HSSFWorkbook) {
workbook.write(new FileOutputStream("ExcelCalculateTimeValues.xls"));
} else if (workbook instanceof XSSFWorkbook) {
workbook.write(new FileOutputStream("ExcelCalculateTimeValues.xlsx"));
}
workbook.close();
}
}
I want to import Excel data to Microsoft Dynamics Ax. I've used this code from this site:
http://axpedia.blogspot.com.tr/2013/02/import-from-excel-file-using-x-in-ax.html
but when i try to run i get this error:
SysExcellworksheet could not start (C)\Classes\SysExcellWorksheets\cells(C)\Jobs\ProductType (line 35)
I am newbie Can you help me about this?
static void ProductType(Args _args)
{
SysExcelApplication application;
SysExcelWorkbooks workbooks;
SysExcelWorkbook workbook;
SysExcelWorksheets worksheets;
SysExcelWorksheet worksheet;
SysExcelCells cells;
COMVariantType type;
Name name;
FileName filename;
ProductType productType;
int row;
int _productTypeId;
str _productType;
str _description;
;
application = SysExcelApplication::construct();
workbooks = application.workbooks();
//specify the file path that you want to read
filename = "Path\\filename.xlsx";
try
{
workbooks.open(filename);
}
catch (Exception::Error)
{
throw error("File cannot be opened.");
}
workbook = workbooks.item(1);
worksheets = workbook.worksheets();
worksheet = worksheets.itemFromNum(4); //Here 3 is the worksheet Number
cells = worksheet.cells();
do
{
row++;
_productTypeId = any2int(cells.item(row, 1).value().toString());
_productType = cells.item(row, 2).value().bStr();
_description = cells.item(row, 3).value().bStr();
productType.ID = _productTypeId;
productType.ProductType = _productType;
productType.Description = _description;
productType.insert();
type = cells.item(row+1, 1).value().variantType();
}
while (type != COMVariantType::VT_EMPTY);
application.quit();
}
You probably translated the error, the exact error when I test this is:
SysExcelWorksheet object not initialized.
This is probably because on the following line you are trying to retrieve the 4th worksheet of the excel, but your excel file has less:
worksheet = worksheets.itemFromNum(4);
If your data is on the first worksheet, use '1' instead of '4':
worksheet = worksheets.itemFromNum(1);