I have some dataTables on the web page and I'd like to export all to an excel file, like the web page images:
I'd like to export the footer like showed in page. I try to use rendered and exportable,both with boolean attribute, but no way.
What might be the reason of such behaviour?
I use the customExport, doing the steps on the link Steps to Custom Exporter
When I debug the code, I see the mode to create the footers on the document exporter, which it's not consist the tag exportable (isExportable()). Into the method "tableColumnGroup(Sheet sheet, DataTable table, String facetType){", of the class ExcelCustomExporter, I need to add an if: "if(column.isExportable()){" to create a cell and add value to this, and another if, the same way, to increment the variable using in the method for(i++); only the if is true I create the cell, add value and increment the variable i.
See below the code modified:
protected void tableColumnGroup(Sheet sheet, DataTable table, String facetType) {
ColumnGroup cg = table.getColumnGroup(facetType);
List<UIComponent> headerComponentList = null;
if (cg != null) {
headerComponentList = cg.getChildren();
}
if (headerComponentList != null) {
for (UIComponent component : headerComponentList) {
if (component instanceof org.primefaces.component.row.Row) {
org.primefaces.component.row.Row row = (org.primefaces.component.row.Row) component;
int sheetRowIndex = sheet.getLastRowNum() + 1;
Row xlRow = sheet.createRow(sheetRowIndex);
int i = 0;
for (UIComponent rowComponent : row.getChildren()) {
UIColumn column = (UIColumn) rowComponent;
String value = null;
if (facetType.equalsIgnoreCase("header")) {
value = column.getHeaderText();
} else {
value = column.getFooterText();
}
int rowSpan = column.getRowspan();
int colSpan = column.getColspan();
Cell cell = xlRow.getCell(i);
if (rowSpan > 1 || colSpan > 1) {
if (rowSpan > 1) {
cell = xlRow.createCell((short) i);
Boolean rowSpanFlag = false;
for (int j = 0; j < sheet.getNumMergedRegions(); j++) {
CellRangeAddress merged = sheet.getMergedRegion(j);
if (merged.isInRange(sheetRowIndex, i)) {
rowSpanFlag = true;
}
}
if (!rowSpanFlag) {
cell.setCellValue(value);
cell.setCellStyle(facetStyle);
sheet.addMergedRegion(new CellRangeAddress(
sheetRowIndex, //first row (0-based)
sheetRowIndex + (rowSpan - 1), //last row (0-based)
i, //first column (0-based)
i //last column (0-based)
));
}
}
if (colSpan > 1) {
cell = xlRow.createCell((short) i);
for (int j = 0; j < sheet.getNumMergedRegions(); j++) {
CellRangeAddress merged = sheet.getMergedRegion(j);
if (merged.isInRange(sheetRowIndex, i)) {
cell = xlRow.createCell((short) ++i);
}
}
cell.setCellValue(value);
cell.setCellStyle(facetStyle);
sheet.addMergedRegion(new CellRangeAddress(
sheetRowIndex, //first row (0-based)
sheetRowIndex, //last row (0-based)
i, //first column (0-based)
i + (colSpan - 1) //last column (0-based)
));
i = i + colSpan - 1;
}
} else {
//TODO TRATAR E VERIRIFICAR SE O VALUE PODE SER EXIBIDO
if (column.isExportable()) {
cell = xlRow.createCell((short) i);
for (int j = 0; j < sheet.getNumMergedRegions(); j++) {
CellRangeAddress merged = sheet.getMergedRegion(j);
if (merged.isInRange(sheetRowIndex, i)) {
cell = xlRow.createCell((short) ++i);
}
}
cell.setCellValue(value);
cell.setCellStyle(facetStyle);
}
}
if (column.isExportable()) {
i++;
}
}
}
}
}
Screnshoot, but the JAN to MAY:
Related
Problem
How to add some part of data from source excel sheet to the destination excel sheet using Apache POI(XSSF Format)?Excel sheet contains merged columns.
Requirement:
Requirement is not only to copy the row but also to put the data into desired Excel cell(desired column) of the destination sheet.
Note
-Copying row to desired row location in destination excel sheet is achievable. Problem is to first merge the cell as per source sheet in destination sheet and then put data into desired merged excel cell.
- Merged Columns could vary in a row.
Here is the source code, half referred and half written.
public static void copyNodeFrmtSrcToDest(XSSFSheet srcSheet, XSSFSheet destSheet, XSSFRow srcRowStart,XSSFRow srcRowEnd
,XSSFRow destRowStart, int destCellStart, Map<Integer, XSSFCellStyle> styleMap){
/*Check if there is only one row to be pasted*/
int noOfRows = srcRowEnd.getRowNum() - srcRowStart.getRowNum();
/*Check if there is only one row to be pasted*/
if(noOfRows == 0)
{
/*Copy a single row*/
copyRow(srcSheet,destSheet,srcRowStart,destRowStart,destCellStart,styleMap);
return;
}
for (int i = 0;i <= noOfRows ;i++)//For every row
{
/*Get rows from source sheet and increment it*/
XSSFRow srcIntermediateRow = srcSheet.getRow(srcRowStart.getRowNum() + i);
if(destRowStart == null)
{
try {
throw new RowNotFoundError("Row has not been found in the sheet.Kindly create a row.");
} catch (RowNotFoundError e) {
e.printStackTrace();
System.out.println(e.toString());
}
}
if(i!=0)//Assuming destRowStart has been created by user of the API
{
/*Create a new row*/
destRowStart = destSheet.createRow(destRowStart.getRowNum()+1);
}
copyRow(srcSheet,destSheet,srcIntermediateRow,destRowStart,destCellStart,styleMap);
}
}
public static void copyRow(XSSFSheet srcSheet, XSSFSheet destSheet, XSSFRow srcRow, XSSFRow destRow, int destCellStart,
Map<Integer, XSSFCellStyle> styleMap) {
int count = 1;
Set<CellRangeAddress> mergedRegions = new HashSet<CellRangeAddress>();
CellRangeAddress previousMergedRegion =null;
destRow.setHeight(srcRow.getHeight());
for (int j = srcRow.getFirstCellNum(); j <= srcRow.getLastCellNum(); j++) {
int mergedDiff;
XSSFCell oldCell = srcRow.getCell(j);
XSSFCell newCell;
if(j == srcRow.getFirstCellNum()){
newCell = destRow.getCell(destCellStart);}
else
{
newCell = destRow.getCell(destCellStart + count);
}
if (oldCell != null) {
if (newCell == null) {
if(j == srcRow.getFirstCellNum()){
newCell = destRow.createCell(destCellStart);//Keeping the new cell as the first one.
copyCell(oldCell, newCell, styleMap);
}
else{
newCell = destRow.createCell(destCellStart + count);
count = count + 1;
copyCell(oldCell, newCell, styleMap);}
}
CellRangeAddress mergedRegion = getMergedRegion(srcSheet, srcRow.getRowNum(),oldCell.getColumnIndex());
if(previousMergedRegion != null && mergedRegion != null)
{
mergedDiff = mergedRegion.getLastColumn() - mergedRegion.getFirstColumn();
if(!previousMergedRegion.equals(mergedRegion))
{
destCellStart = destCellStart + mergedDiff + 1;
count = 1;
}
}
if (mergedRegion != null) {
previousMergedRegion = mergedRegion.copy();
mergedDiff = mergedRegion.getLastColumn() - mergedRegion.getFirstColumn();
CellRangeAddress newMergedRegion = new CellRangeAddress(destRow.getRowNum(),destRow.getRowNum()
,destCellStart,destCellStart + mergedDiff);
if (isNewMergedRegion(newMergedRegion, mergedRegions))
{
mergedRegions.add(newMergedRegion);
destSheet.addMergedRegion(newMergedRegion);
}
}
}
}
}
public static void copyCell(XSSFCell oldCell, XSSFCell newCell, Map<Integer, XSSFCellStyle> styleMap) {
if(styleMap != null) {
if(oldCell.getSheet().getWorkbook() == newCell.getSheet().getWorkbook()){
newCell.setCellStyle(oldCell.getCellStyle());
} else{
int stHashCode = oldCell.getCellStyle().hashCode();
XSSFCellStyle newCellStyle = styleMap.get(stHashCode);
if(newCellStyle == null){
newCellStyle = newCell.getSheet().getWorkbook().createCellStyle();
newCellStyle.cloneStyleFrom(oldCell.getCellStyle());
styleMap.put(stHashCode, newCellStyle);
}
newCell.setCellStyle(newCellStyle);
}
}
switch(oldCell.getCellTypeEnum()) {
case STRING:
newCell.setCellValue(oldCell.getStringCellValue());
break;
case NUMERIC:
newCell.setCellValue(oldCell.getNumericCellValue());
break;
case BLANK:
newCell.setCellValue(oldCell.getStringCellValue());
break;
case BOOLEAN:
newCell.setCellValue(oldCell.getBooleanCellValue());
break;
case ERROR:
newCell.setCellErrorValue(oldCell.getErrorCellValue());
break;
case FORMULA:
newCell.setCellFormula(oldCell.getCellFormula());
break;
default:
break;
}
}
public static CellRangeAddress getMergedRegion(XSSFSheet sheet, int rowNum, int cellNum) {
for (int i = 0; i < sheet.getNumMergedRegions(); i++) {
CellRangeAddress merged = sheet.getMergedRegion(i);
if (merged.isInRange(rowNum, cellNum)) {
return merged;
}
}
return null;
}
private static boolean isNewMergedRegion(CellRangeAddress newMergedRegion, Set<CellRangeAddress> mergedRegions)
{
if(mergedRegions.isEmpty())
{
return true;
}
return !mergedRegions.contains(newMergedRegion);
}
}
It is working fine for some testcases but not for all.
I have an app with a route datatable. The data is csv file. I like
highlight a row in a table in codenameone by changing the backgroundcolor of the row. How can I do this?
My Code is
String File_Name ="/route.csv";
//"/root/sdcard/Pictures/route.csv";
File f= new File (File_Name);
if (f.exists())
InputStream is = Display.getInstance().getResourceAsStream(getClass(), File_Name );
CSVParser parser = new CSVParser();
String[][] data = parser.parse(is);
String[] columnNames = new String[data[0].length];
l = data.length;
for(int iter= 0 ; iter < columnNames.length ; iter++) {
if (iter== 0) {
columnNames[iter] = "Naam";
}
else if (iter== 1) {
columnNames[iter] = "Latitude";
}
else if (iter== 2) {
columnNames[iter] = "Longitude";
}
}
tm = new DefaultTableModel(columnNames, data);
}
}
catch (IOException err){
err.printStackTrace();
}
further in the code
Table tm2 = new Table(tm)
EDIT solved myself
I edited the table definiton tm2 and added the variable A. A is the row which is highlighted
Table tm2 = new Table(tm) {
#Override
public Component createCell(Object value, int row, int column, boolean editable) { // (1)
Component cell;
cell = super.createCell(value, row, column, editable);
if(row > a-1 && row < a+1) { // (5)
// pinstripe effect
cell.getAllStyles().setBgColor(0xe2f30d);
cell.getAllStyles().setBgTransparency(255);
}
return cell;
}
Changing the cell color is discussed in the developer guide as you probably discovered the pinstripe sample from there.
The full sample from the developer guide is this:
Table table = new Table(model) {
#Override
protected Component createCell(Object value, int row, int column, boolean editable) {
Component cell;
if(row == 1 && column == 1) {
Picker p = new Picker();
p.setType(Display.PICKER_TYPE_STRINGS);
p.setStrings("Row B can now stretch", "This is a good value", "So Is This", "Better than text field");
p.setSelectedString((String)value);
p.setUIID("TableCell");
p.addActionListener((e) -> getModel().setValueAt(row, column, p.getSelectedString()));
cell = p;
} else {
cell = super.createCell(value, row, column, editable);
}
if(row > -1 && row % 2 == 0) {
// pinstripe effect
cell.getAllStyles().setBgColor(0xeeeeee);
cell.getAllStyles().setBgTransparency(255);
}
return cell;
}
#Override
protected TableLayout.Constraint createCellConstraint(Object value, int row, int column) {
TableLayout.Constraint con = super.createCellConstraint(value, row, column);
if(row == 1 && column == 1) {
con.setHorizontalSpan(2);
}
con.setWidthPercentage(33);
return con;
}
};
i have a piece of code to right into excel sheet,it is based on the row number and column name specified ,my issue is that if a column name is null then value will not set in the rest of the columns.
in this excel no value get added after Column 'D'
Below is my code
public boolean setExcelData(String sheetName, String colName, int rowNum, String data) throws AutoException {
dataFile();
try {
if (rowNum <= 0)
throw new AutoException(EXCEPTIION);
int index = wb.getSheetIndex(sheetName);
int colNum = -1;
if (index == -1)
throw new AutoException(EXCEPTIION);
XSSFSheet sheet = wb.getSheetAt(index);
Row row = sheet.getRow(0);
for (int i = 0; i < row.getLastCellNum(); i++) {
System.out.println(row.getCell(i));
if (row.getCell(i) == null) {
throw new AutoException(EXCEPTIION);
} else if (row.getCell(i).getStringCellValue().trim().equals(colName)) {
colNum = i;
break;
}
}
if (colNum == -1)
throw new AutoException(EXCEPTIION);
sheet.autoSizeColumn(colNum);
row = sheet.getRow(rowNum - 1);
if (row == null)
row = sheet.createRow(rowNum - 1);
Cell cell = row.getCell(colNum);
if (cell == null)
cell = row.createCell(colNum);
cell.setCellValue(data);
FileOutputStream fileOut = new FileOutputStream(excelFilePath);
wb.write(fileOut);
fileOut.close();
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
try {
wb.close();
in.close();
} catch (Exception e) {
}
}
return true;
}
Any one can help me out.
thanks in advance
skip the for loop iteration if columnname is null
for (int i = 0; i < row.getLastCellNum(); i++) {
System.out.println(row.getCell(i));
if (String.IsNullOrEmpty(colName))
continue;
if (row.getCell(i) == null) {
throw new AutoException(EXCEPTIION);
} else if (row.getCell(i).getStringCellValue().trim().equals(colName)) {
colNum = i;
break;
}
}
I would like to generate a HTML table from an excel file. The EPPlus package provides a .net API for manipulating excel file. I would be happy to know whether it is possible to generate a HTML table code from an Excel file using EPPlus? I couldn't find anything on the documentation, but intuition tells me that there should be a way to do it
Thank you!
If you are looking for something built into EPPlus, I havent seen anything that will export directly HTML.
Best thing would be to bring in the Excel file to EPPlus and extract the data to a collection or DataTable. That should be pretty straight forward.
From there, there is plenty of documentation on how to get that to an html table. Quick search turned up this as the first hit:
Datatable to html Table
I wrote some code, you can try this.
static void Main(string[] args)
{
ExcelPackage p = new ExcelPackage(new System.IO.FileInfo("X.XLSX"));
var sheet = p.Workbook.Worksheets["HMTD"];
var noOfCol = sheet.Dimension.End.Column;
var noOfRow = sheet.Dimension.End.Row;
StringBuilder s = new StringBuilder();
s.Append("<table>");
for (int i = 1; i < noOfRow; i++)
{
s.Append("<tr>");
for (int j = 1; j < noOfCol; j++)
{
int colspan = 1;
int rowspan = 1;
if (!sheet.Cells[i, j].Merge || (sheet.Cells[i, j].Merge && isFirstMergeRange(sheet, sheet.Cells[i, j].Address, ref colspan, ref rowspan)))
{
s.Append("<td rowspan='" + rowspan + "' colspan='" + colspan + "'>");
if(sheet.Cells[i,j] != null && sheet.Cells[i,j].Value != null)
s.Append(sheet.Cells[i,j].Value.ToString());
s.Append("</td>");
}
}
s.Append("</tr>");
}
s.Append("</table>");
System.IO.File.WriteAllText("duc.html",s.ToString());
Console.ReadKey();
}
private static bool isFirstMergeRange(ExcelWorksheet sheet, string address, ref int colspan, ref int rowspan)
{
colspan = 1;
rowspan = 1;
foreach (var item in sheet.MergedCells)
{
var s = item.Split(':');
if (s.Length > 0 && s[0].Equals(address)){
ExcelRange range = sheet.Cells[item];
colspan = range.End.Column - range.Start.Column;
rowspan = range.End.Row - range.Start.Row;
if(colspan == 0) colspan = 1;
if(rowspan == 0) rowspan = 1;
return true;
}
}
return false;
}
Based on the answer from Duc Tran Minh, it works fine for me after I modified the code like this:
static void Main(string[] args)
{
ExcelPackage p = new ExcelPackage(new System.IO.FileInfo("X.XLSX"));
var sheet = p.Workbook.Worksheets["HMTD"];
var noOfCol = sheet.Dimension.End.Column;
var noOfRow = sheet.Dimension.End.Row;
StringBuilder s = new StringBuilder();
s.Append("<table>");
for (int i = 1; i <= noOfRow; i++)
{
s.Append("<tr>");
for (int j = 1; j <= noOfCol; j++)
{
int colspan = 1;
int rowspan = 1;
if (!sheet.Cells[i, j].Merge || (sheet.Cells[i, j].Merge && isFirstMergeRange(sheet, sheet.Cells[i, j].Address, ref colspan, ref rowspan)))
{
s.Append("<td rowspan='" + rowspan + "' colspan='" + colspan + "'>");
if(sheet.Cells[i,j] != null && sheet.Cells[i,j].Value != null)
s.Append(sheet.Cells[i,j].Value.ToString());
s.Append("</td>");
}
}
s.Append("</tr>");
}
s.Append("</table>");
System.IO.File.WriteAllText("duc.html",s.ToString());
Console.ReadKey();
}
bool isFirstMergeRange(ExcelWorksheet sheet, string address, ref int colspan, ref int rowspan)
{
colspan = 1;
rowspan = 1;
foreach (var item in sheet.MergedCells)
{
var s = item.Split(':');
if (s.Length > 0 && s[0].Equals(address))
{
ExcelRange range = sheet.Cells[item];
colspan = range.End.Column - range.Start.Column + 1;
rowspan = range.End.Row - range.Start.Row + 1;
return true;
}
}
return false;
}
im struggeling for below scenario.
Application displayed records of 100 suppliers in one table have three columns namely as ID,Company name and Subscription name.
i want to take input from my excel sheet say company name"xyz" and using that input i have to click on subscription name details link so application will navigates me next page.
Sample code i have created as below:
`public static void main(String[] args) throws BiffException, IOException, Exception {
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
//Workbook location
Workbook wBook = Workbook.getWorkbook(new File("C:\Users\amit.bhagwat\Documents\TestData\SampleData.xls"));
//get sheet
jxl.Sheet Sheet = wBook.getSheet(0);
//loop
for(int i=1; i<Sheet.getRows(); i++)
{
driver.get("http://206.132.42.243/Web");
driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
driver.findElement(By.xpath("//input[#id='UserName']")).sendKeys(Sheet.getCell(0, i).getContents());
driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
driver.findElement(By.xpath("//input[#id='Password']")).sendKeys(Sheet.getCell(1, i).getContents());
driver.findElement(By.xpath("//input[#id='Password']")).sendKeys(Sheet.getCell(1, i).getContents());
Thread.sleep(40);
driver.findElement(By.xpath("//input[#name='Login']")).click();
driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
driver.findElement(By.xpath("//a[contains(text(),'Task')]")).click();
driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
driver.findElement(By.xpath("//a[contains(text(),'Data Checking')]")).click();
jxl.Sheet Sheet2 = wBook.getSheet(0);
WebElement kancheck = driver.findElement(By.name("Grant & Brown"));
kancheck.click();
System.out.println(kancheck.isSelected());
driver.findElement(By.xpath("//a[contains(text(),'Data Checking')]")).sendKeys(Sheet2.getCell(1, i).getContents());
Thread.sleep(40);` enter code here
As far as I could understand, you are trying to read the file from a remote location and then read the information from it. It would be a good practice if you can use Apache POI library to read contents at run-time.
In my project, I read all the contents from an excel sheet usingApache POI library to set the values of my variables. Here is a code snippet on how i achieved it. Hopefully this will guide you to a proper solution. :)
public void readExcelDoc() throws FileNotFoundException, IOException
{
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream("excelDoc//scripts.xls"));
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0);
HSSFRow row = null;
HSSFCell cell = null;
int rows = 0; // No of rows
// rows = sheet.getPhysicalNumberOfRows();
rows = sheet.getLastRowNum();
int cols = 2; // No of columns
int tmp = 0;
// This trick ensures that we get the data properly even if it doesn't start from first few rows
for(int i = 0; i < 10 || i < rows; i++) {
row = sheet.getRow(i);
if(row != null) {
tmp = sheet.getRow(i).getPhysicalNumberOfCells();
if(tmp > cols) cols = tmp;
}
}
int testRowNo = 0;
String rowName = "Test Name";
String columnValue = " ";
//Iterate through Row and columns here. Excluding 1st row for title names
for(int r = 1; r <= rows; r++) {
row = sheet.getRow(r);
if(row != null) {
//Browse through columns using c
for(int c = 0; c < cols; c++) {
if(c==0) //Only taking data from Cell 0; Ignoring any other inputs
{
cell = row.getCell((short)c);
try
{
if(cell.getStringCellValue().contains(rowName))
{
testRowNo =row.getRowNum();
}
if(testRowNo > 0 )
{
if(cell.getColumnIndex() == 0 && row.getRowNum() > testRowNo && cell.getStringCellValue().length() !=0)
{
try{
String cellValue = cell.getStringCellValue().toLowerCase();
//System.out.println(cellValue);
scriptType.add(cellValue);
}
catch(IllegalStateException e)
{
e.printStackTrace();
scriptType.add(cell.getStringCellValue());
}
}
}
}
catch(NullPointerException e)
{
}
}
if(c==1)
{
cell = row.getCell((short)c); //this sets the column number
if(testRowNo == 0)
{
try{
String cellValue = cell.getStringCellValue();
//System.out.println(cellValue);
columnValue = cellValue;
}
catch(IllegalStateException e)
{
String cellValue = cell.toString();
columnValue = cellValue;
}
catch(NullPointerException e)
{
String cellValue = nodata;
columnValue = cellValue;
}
}
}
if(c==2)
{
cell = row.getCell((short)c); //this sets the column number
if(testRowNo == 0)
{
try{
String cellValue = cell.getStringCellValue();
//System.out.println(cellValue);
inputParameters.put(cellValue, columnValue);
}
catch(IllegalStateException e)
{
String cellValue = cell.toString();
inputParameters.put(cellValue, columnValue);
}
catch(NullPointerException e)
{
String cellValue = nodata;
inputParameters.put(cellValue, columnValue);
}
}
}
}
}
}
System.out.println("---------The parameters set from excel are : ---------");
#SuppressWarnings("rawtypes")
Iterator iterator = inputParameters.keySet().iterator();
while (iterator.hasNext()) {
String key = iterator.next().toString();
String value = inputParameters.get(key).toString();
System.out.println(key + " : " + value);
}
}