Tracking row numbers to display partial excel Apache POI - apache-poi

My requirement is to read an excel sheet as a super data set and display part of it depending on the start and end text as values in a certain column. I am able to iterate through the whole sheet but unable to track the row numbers which I can iterate through later to iterate through partial sheet.
Below is my JSP code
<%#page import="org.apache.poi.ss.util.CellReference"%>
<%#page import="java.util.regex.Matcher"%>
<%#page import="java.util.regex.Pattern"%>
<%#page import="org.apache.poi.xssf.usermodel.XSSFCell"%>
<%#page import="java.text.SimpleDateFormat"%>
<%#page import="org.apache.poi.ss.usermodel.DateUtil"%>
<%#page import="org.apache.poi.ss.usermodel.CellType"%>
<%#page import="org.apache.poi.ss.usermodel.Cell"%>
<%#page import="org.apache.poi.ss.usermodel.Row"%>
<%#page import="org.apache.poi.ss.usermodel.Sheet"%>
<%#page import="org.apache.poi.xssf.usermodel.XSSFWorkbook"%>
<%#page import="org.apache.poi.ss.usermodel.Workbook"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%#page import="java.io.*"%>
<%#page import="java.util.*"%>
<%#page import="org.apache.poi.hssf.usermodel.HSSFSheet"%>
<%#page import="org.apache.poi.hssf.usermodel.HSSFWorkbook"%>
<%#page import="org.apache.poi.hssf.usermodel.HSSFRow"%>
<%#page import="org.apache.poi.hssf.usermodel.HSSFCell"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<table border="4">
<%
short a = 0;
short b = 1;
short c = 2;
short d = 3;
short ee = 4;
short f = 5;
short g = 6;
short h = 7;
short l = 8;
short m = 9;
int i = 0;
List<Integer> rowCountList = new ArrayList<Integer>();
String value1 = "", value2 = "", value3 = " ", value4 = "", value5 = "", value6 = "", value7 = "", value8 = "", value9 = "", value10 = "";
String filename = "Temp.xlsx";
if (filename != null && !filename.equals(
"")) {
try {
FileInputStream fs = new FileInputStream(new File(filename));
Workbook wb = new XSSFWorkbook(fs);
for (int k = 0; k < wb.getNumberOfSheets(); k++) {
int j = i + 1;
Sheet sheet = wb.getSheetAt(k);
int rows = sheet.getPhysicalNumberOfRows();
System.out.println("Rows:" + rows);
for (int r = 0; r < rows; r++) {
value1 = "";
value2 = "";
value3 = " ";
value4 = "";
value5 = "";
value6 = "";
value7 = "";
value8 = "";
value9 = "";
value10 = "";
System.out.println("row no:" + r);
Row row = sheet.getRow(r);
// int cells = row.getPhysicalNumberOfCells();
// System.out.println(cells);
out.write("<br>");
Cell cell1 = row.getCell(a, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
if (cell1.getCellType() != CellType.BLANK) {
switch (cell1.getCellType()) {
case STRING:
value1 = cell1.getStringCellValue();
break;
case NUMERIC:
value1 = " " + cell1.getNumericCellValue();
break;
}
}
Cell cell2 = row.getCell(b, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
if (cell2.getCellType() != CellType.BLANK) {
switch (cell2.getCellType()) {
case STRING:
value2 = cell2.getStringCellValue();
break;
case NUMERIC:
if (DateUtil.isCellDateFormatted(cell2)) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
value2 = "" + dateFormat.format(cell2.getDateCellValue());
} else {
value2 = " " + cell2.getNumericCellValue();
}
break;
}
}
Cell cell3 = row.getCell(c, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
switch (cell3.getCellType()) {
case STRING:
value3 = cell3.getStringCellValue();
break;
case NUMERIC:
value3 = " " + cell3.getNumericCellValue();
break;
}
Cell cell4 = row.getCell(d, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
switch (cell4.getCellType()) {
case STRING:
value4 = cell4.getStringCellValue();
break;
case NUMERIC:
value4 = " " + cell4.getNumericCellValue();
break;
}
Cell cell5 = row.getCell(ee, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
switch (cell5.getCellType()) {
case STRING:
value5 = cell5.getStringCellValue();
break;
case NUMERIC:
value5 = " " + cell5.getNumericCellValue();
break;
}
Cell cell6 = row.getCell(f, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
switch (cell6.getCellType()) {
case STRING:
value6 = cell6.getStringCellValue();
break;
case NUMERIC:
value6 = " " + cell6.getNumericCellValue();
break;
}
Cell cell7 = row.getCell(g, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
switch (cell7.getCellType()) {
case STRING:
value7 = cell7.getRichStringCellValue().getString();
break;
case NUMERIC:
value7 = " " + cell7.getNumericCellValue();
break;
}
Cell cell8 = row.getCell(h, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
// if (cell8.getCellType() != CellType.BLANK) {
switch (cell8.getCellType()) {
case STRING:
value8 = cell8.getRichStringCellValue().getString();
**if (value8.equalsIgnoreCase("Execution Start")) {
System.out.println(row.getRowNum());
for (int x = row.getRowNum(); x < sheet.getLastRowNum(); x++) {
Row rowx = sheet.getRow(x);
Cell cellx = rowx.getCell(h, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
if (!cellx.getRichStringCellValue().getString().equalsIgnoreCase("Execution End")) {
rowCountList.add(x);**
}
}
}
// System.out.println(value8);
break;
case NUMERIC:
value8 = " " + cell8.getNumericCellValue();
break;
}
Cell cell9 = row.getCell(l, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
switch (cell9.getCellType()) {
case STRING:
value9 = cell9.getRichStringCellValue().getString();
break;
case NUMERIC:
value9 = " " + cell9.getNumericCellValue();
break;
}
Cell cell10 = row.getCell(m, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
switch (cell10.getCellType()) {
case STRING:
value10 = cell10.getRichStringCellValue().getString();
break;
case NUMERIC:
value10 = " " + cell10.getNumericCellValue();
break;
}
%>
<tr><td><%=value1%></td><td><%=value2%></td><td><%=value3%></td><td><%=value4%></td><td><%=value5%></td><td><%=value6%></td><td><%=value7%></td>
<td><%=value8%></td><td><%=value9%></td><td><%=value10%></td></tr>
<%
i++;
}
System.out.println(rowCountList);
}
} catch (Exception e) {
System.out.println(e);
}
}
%>
</table>
</body>
</html>
value8 basis I need to extract certain rows and display, am not able to track the row numbers as I get an NPE on the line Cell cellx = rowx.getCell(h, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
Please advise

I achieved tracking of rows through two flags that demarcate the start and end of row data that I need to extract, using those row numbers I again iterate through sheet and display the extracted data

Related

Excel loses styles and formating after writing certain rows using apache poi library

I am trying to create a excel file(.xls) while writing a excel for tolal of 9000 rows, after row number 3000 all the styles and formatting are lost.
I have tried to get the number of cellstyle after writing the complete workbook by using workbook.getNumCellStyles(), it returns 2091.
It is clear that the number of cellstyle are not exceeded(i.e are less than 4000)
Still the styling is lost.
Please help me understand why would this happen?
I have created a Sample code, below this fails even if i am creating 75 CellStyle Objects.
public class ExcelSheet {
static Workbook workbook;
static Sheet spreadsheet;
static CellStyle tempCellStyle;
static Map<Integer, CellStyle> styles = new HashMap<Integer, CellStyle>();
static boolean flag = false;
public static void main(String[] args) throws IOException {
workbook = new HSSFWorkbook();
spreadsheet = workbook.createSheet(" Employee Info ");
Row row;
System.out.println(" Writing data to excel...");
for (int i = 1; i < 500; i++) {
row = spreadsheet.createRow(i);
createCells(row, i);
}
for (int i = 0; i < 10; i++) {
spreadsheet.setColumnWidth(i, 4500);
}
FileOutputStream out = new FileOutputStream(new File("E:\\Dan\\Writesheet.xls"));
System.out.println(" No. of cell styles : " + workbook.getNumCellStyles());
System.out.println(" No. of font styles : " + workbook.getNumberOfFonts());
workbook.write(out);
out.close();
}
private static void createCells(Row row, int rowNo) {
for (int i = 0; i < 10; i++) {
Cell cell = row.createCell(i);
try {
writeData(cell, i, rowNo);
} catch (Exception e) {
System.out.println("Exception : " + e);
}
}
}
private static void writeData(Cell cell, int i, int rowNo) throws Exception {
CellStyle style;
if (workbook.getNumCellStyles() < 75) {
style = createStyleObject();
} else {
style = null;
}
switch (i) {
case 0:
if (style == null) {
style = styles.get(0);
} else {
styles.put(0, style);
}
cell.setCellValue(rowNo);
cell.setCellType(Cell.CELL_TYPE_NUMERIC);
cell.setCellStyle(style);
break;
case 1:
if (style == null) {
style = styles.get(1);
} else {
styles.put(1, style);
}
cell.setCellValue("Test Data " + rowNo);
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellStyle(style);
styles.put(0, style);
break;
case 2:
if (style == null) {
style = styles.get(2);
} else {
styles.put(2, style);
}
DataFormat poiFormat = spreadsheet.getWorkbook().createDataFormat();
String excelFormatPattern = DateFormatConverter.convert(Locale.US, "yyyy-MM-dd");
style.setDataFormat(poiFormat.getFormat(excelFormatPattern));
cell.setCellValue(new Date(rowNo % 10, rowNo % 12, rowNo % 28, rowNo % 12, rowNo % 60, rowNo % 60));
cell.setCellStyle(style);
break;
case 3:
if (style == null) {
style = styles.get(3);
} else {
styles.put(3, style);
}
cell.setCellValue(rowNo + rowNo);
cell.setCellType(Cell.CELL_TYPE_NUMERIC);
cell.setCellStyle(style);
break;
case 4:
if (style == null) {
style = styles.get(4);
} else {
styles.put(4, style);
}
cell.setCellValue("Sample Text " + rowNo);
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellStyle(style);
break;
case 5:
if (style == null) {
style = styles.get(5);
} else {
styles.put(5, style);
}
DataFormat poiFormat1 = spreadsheet.getWorkbook().createDataFormat();
String excelFormatPattern1 = DateFormatConverter.convert(Locale.US, "yyyy-MM-dd");
style.setDataFormat(poiFormat1.getFormat(excelFormatPattern1));
cell.setCellValue(new Date(rowNo % 18, rowNo % 12, rowNo % 28, rowNo % 12, rowNo % 60, rowNo % 60));
cell.setCellStyle(style);
break;
case 6:
if (style == null) {
style = styles.get(6);
} else {
styles.put(6, style);
}
cell.setCellValue(rowNo + i);
cell.setCellType(Cell.CELL_TYPE_NUMERIC);
cell.setCellStyle(style);
break;
case 7:
if (style == null) {
style = styles.get(7);
} else {
styles.put(7, style);
}
cell.setCellValue("Exports Data " + rowNo);
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellStyle(style);
break;
case 8:
if (style == null) {
style = styles.get(8);
} else {
styles.put(8, style);
}
DataFormat poiFormat2 = spreadsheet.getWorkbook().createDataFormat();
String excelFormatPattern2 = DateFormatConverter.convert(Locale.US, "yyyy-MM-dd");
style.setDataFormat(poiFormat2.getFormat(excelFormatPattern2));
cell.setCellValue(new Date(rowNo % 25, rowNo % 12, rowNo % 28, rowNo % 12, rowNo % 60, rowNo % 60));
cell.setCellStyle(style);
break;
case 9:
if (style == null) {
style = styles.get(9);
} else {
styles.put(9, style);
}
DataFormat poiFormat3 = spreadsheet.getWorkbook().createDataFormat();
String excelFormatPattern3 = DateFormatConverter.convert(Locale.US, "yyyy-MM-dd");
style.setDataFormat(poiFormat3.getFormat(excelFormatPattern3));
cell.setCellValue(new Date());
cell.setCellStyle(style);
break;
default:
if (style == null) {
style = styles.get(7);
} else {
styles.put(7, style);
}
cell.setCellValue("Default Value " + rowNo);
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellStyle(style);
break;
}
}
private static CellStyle createStyleObject() {
Workbook workbook = spreadsheet.getWorkbook();
CellStyle style = (HSSFCellStyle) workbook.createCellStyle();
style.setFillPattern(CellStyle.SOLID_FOREGROUND);
style.setFillForegroundColor((short) 67);
style.setWrapText(true);
return style;
}
}
Don't create CellStyle for every cell in the workbook. Instead prepare all possible and unique CellStyles and reuse them.
E.g.:
var cellStyle = createStyleObject();
// ... some customization of the above style
for (int i = 0; i < 10; i++) {
Cell cell = row.createCell(i);
cell.setStyle(cellStyle);
}

LinqPad customize excel export

I would like to modify the export to excel function of LinqPad. I want the output to be on rows instead of columns. Example current format:
Result1
value1
value2
value3
Result2
rvalue1
rvalue2
But I want it in the following format:
Result1 Result2
value1 rvalue1
value2 rvalue2
value3
Try this one.
string Input = #"
Result1
value1
value2
value3
Result2
rvalue1
rvalue2
".Trim();
void Main()
{
var isNextColumn = true;
var theList = Input.Split('\n').Select(s => {
var anon = new { IsColumn = isNextColumn, Value = s.Trim() };
isNextColumn = string.IsNullOrWhiteSpace(s);
return anon;
}).Where(w => !string.IsNullOrWhiteSpace(w.Value)).ToList();
var table = new DataTable("Your Sheet");
theList.Where(w => w.IsColumn).ToList().ForEach(f => table.Columns.Add(f.Value));
var rowCounter = 1;
var columnName = string.Empty;
theList.ForEach(f => {
if(f.IsColumn)
{
columnName = f.Value;
rowCounter = 0;
} else {
if(table.Rows.Count <= rowCounter)
{
var newRow = table.NewRow();
newRow[columnName] = f.Value;
table.Rows.Add(newRow);
} else table.Rows[rowCounter][columnName] = f.Value;
++rowCounter;
}
});
table.Dump();
}

Selenium Webdriver How to select records from table by fetching Excel Input

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);
}
}

asp gridview export to excel hide column

Can someone please take a look at my code? this code works perfectly but i want to remove the 1st and 2nd column when the data exported to excel. i try GridView1.Columns[0].Visible = false; but its not working.
here's my aspx
<%# Page Title="VRQ" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="EmployeePage.aspx.cs" Inherits="EmployeePage"%>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<script language="javascript" type="text/javascript">
function Button1_onclick() {
//open new window set the height and width =0,set windows position at bottom
var a = window.open ('','','left =' + screen.width + ',top=' + screen.height + ',width=0,height=0,toolbar=0,scrollbars=0,status=0');
//write gridview data into newly open window
a.document.write(document.getElementById('innerdata').innerHTML);
a.document.close();
a.focus();
//call print
a.print();
a.close();
return false;
}
function OpenFile(KEYW) {
window.open("ResumePage.aspx?bid=" + KEYW, "ResumeContext");
}
</script>
<asp:Button ID="btnbacksearch" runat="server" Text="Back to Search"
Width="127px" OnClick="btnbacksearch_Click" CssClass="plainbutton" />
<asp:Button ID="btnExportToExcel" runat="server" OnClick="btnExportToExcel_Click"
Text="Export Results to Excel" Width="174px" CssClass ="plainbutton" />
<asp:Button
ID="btnGenerateSF" runat="server" OnClick="btnGenerateSF_Click"
Text="Generate Resume" Width="137px" CssClass ="plainbutton"
Visible="False" />
<asp:DropDownList ID="ddStatus" runat="server"
onselectedindexchanged="ddStatus_SelectedIndexChanged" AutoPostBack="True"
Visible="False" Width="150px">
<asp:ListItem Selected="True" Value="Active">Active Personnel</asp:ListItem>
<asp:ListItem Value="Inactive">Inactive Personnel</asp:ListItem>
</asp:DropDownList>
<div style="font-size: 11pt; font-family: Tahoma; text-align:center "><strong>
SEARCH SUMMARY</strong></div>
<div style="font-size: 10pt; font-family: Tahoma; text-align:center ">
<asp:Label ID="LabelCaption" runat="server" Text="Label"></asp:Label>
</div>
<div id = "innerdata" style="size: landscape;" >
<asp:GridView ID="GridView1" runat="server"
CellPadding="4" DataSourceID="SqlDataSource1"
onrowcreated="GridView1_RowCreated"
AllowPaging="True" onpageindexchanging="GridView1_PageIndexChanging"
DataKeyNames="IDNo" AllowSorting="True" Width="100%"
PageSize="30" EmptyDataText="No Existing Records." CssClass="GridView"
onrowcommand="GridView1_RowCommand"
AutoGenerateColumns="False"
onsorted="GridView1_Sorted" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat ="server" ID="lnkSelect" Text="View" CommandName ="Select" CommandArgument='<%# Eval("IDNo") %>' ></asp:LinkButton>
</ItemTemplate>
<ItemStyle Width="20px" HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat ="server" ID="lnkPrintRep1" Text="Project Selection" CommandName ="PrintSF330" CommandArgument='<%# Eval("IDNo") %>' ></asp:LinkButton>
</ItemTemplate>
<ItemStyle Width="70px" HorizontalAlign="Center" />
</asp:TemplateField>
<asp:BoundField DataField="fullname" HeaderText="Name" ReadOnly="True"
SortExpression="fullname" >
<ItemStyle Width="200px" />
</asp:BoundField>
<asp:BoundField DataField="YearsExperience" HeaderText="Experience"
SortExpression="YearsExperience" >
<ItemStyle Width="50px" HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField="Job" HeaderText="Position" SortExpression="Job" >
<ItemStyle Width="200px" />
</asp:BoundField>
<asp:TemplateField HeaderText="Search Results" SortExpression ="SearchDetails">
<ItemTemplate>
<%# HighlightText(Convert.ToString(Eval("SearchDetails"))) %> </ItemTemplate>
<ItemStyle Width="300px" />
</asp:TemplateField>
</Columns>
<RowStyle CssClass="GridRowStyle"/>
<PagerStyle HorizontalAlign="Center" />
<SelectedRowStyle CssClass="GridSelected" />
<HeaderStyle CssClass="GridHeader" Height="10px" />
<PagerStyle CssClass="GridFooterStyle"/>
</asp:GridView></div>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:HRIS_ConnectionString %>"
ProviderName="<%$ ConnectionStrings:HRIS_ConnectionString.ProviderName %>"
SelectCommand="select i.IDNo,concat(lastname,', ',firstname,' ',middlename) as fullname,e.tYrsExperience as YearsExperience,p.Description as Job,'' as SearchDetails FROM employeesinfo i inner join ecd e on e.empid=i.idno
left outer join Position p on p.idno = e.presentjob">
</asp:SqlDataSource>
<vt:MessageBox ID="MessageBox1" runat="server"></vt:MessageBox>
</asp:Content>
and here's my aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;
using System.IO;
using System.Text;
public partial class EmployeePage : System.Web.UI.Page
{
string sqry = ""; string scolumn = "";
string origQry = String.Empty;
public string keyword = "";
public string curAlpha = "";
public int iCtr = 0;
protected void Page_Load(object sender, EventArgs e)
{
if (Session["QRY_CONDITIONS"] == null) Response.Redirect("Default.aspx");
scolumn = Session["QRY_DETAIL"].ToString();
sqry = Session["QRY_CONDITIONS"].ToString();
clsUser user = (clsUser)Session["CurrentUser"];
if (user == null) return;
if (user.IsSuperAdmin && sqry == "ALL")
{
ddStatus.Visible = true;
sqry = string.Format(" where ifnull(i.activestatus,0) = {0}", ddStatus.SelectedIndex == 0 ? "1" : "0") ;
}
else if(sqry == "ALL")
{
ddStatus.Visible = false;
sqry = " where ifnull(i.activestatus,0) = 1 ";
}
origQry = sqry;
if (Request.QueryString["keyword"] != null) keyword = Request.QueryString["keyword"].ToString().TrimEnd().TrimStart();
if (!IsPostBack)
{
if (keyword == "")
{
sqry = sqry + " and i.lastname like 'A%' ";
Session["QRY_alpha"] = " and i.lastname like 'A%' ";
curAlpha = "A";
}
LoadStates();
BindData();
}
}
protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);
curAlpha = (string)ViewState["curAlpha"];
}
protected override object SaveViewState()
{
ViewState["curAlpha"] = curAlpha;
return base.SaveViewState();
}
private void BindData()
{
modPublic myMod = new modPublic();
SqlDataSource1.SelectCommand = "SELECT distinct i.idno,concat(i.lastname,', ',i.firstname,' ',i.middlename) as fullname,e.tYrsExperience as YearsExperience,e.Position as Job," + scolumn + " as SearchDetails FROM employeesinfo i left join ecd e on e.empid=i.idno " +
"left join position p on p.idno = e.presentjob left join firm_location loc on loc.idno = i.firmlocationid " + sqry + " order by i.lastname,i.firstname";
SqlDataSource1.Select(new DataSourceSelectArguments());
object o = myMod.ExecuteScalar("select count(distinct i.idno) as ctr FROM employeesinfo i left join ecd e on e.empid=i.idno " +
"left join position p on p.idno = e.presentjob left join firm_location loc on loc.idno = i.firmlocationid " + origQry + " ");
LabelCaption.Text = o.ToString() + " Record(s) found";
if (keyword == "")
{
GridView1.AllowPaging = false;
GridView1.Columns[5].Visible = false;
}
else
{
GridView1.Columns[5].Visible = true;
}
GridView1.DataBind();
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
BindData();
GridView1.PageIndex = e.NewPageIndex;
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "AlphaPaging")
{
curAlpha = e.CommandArgument.ToString();
sqry = sqry + " and i.lastname like '" + e.CommandArgument + "%'";
Session["QRY_alpha"] = " and i.lastname like '" + e.CommandArgument + "%'";
GridView1.AllowPaging = false;
BindData();
SaveStates();
//this.SqlDataSource1.SelectCommand = "Select * from [Table_1] WHERE theName LIKE '" + e.CommandArgument + "%'";
}
if (e.CommandName == "PrintSF330")
{
SaveStates();
Response.Redirect("~/ReportViewer.aspx?EmpID=" + e.CommandArgument.ToString() + " ");
}
else if (e.CommandName == "Select")
{
SaveStates();
loadECD(e.CommandArgument.ToString());
}
}
//protected override object SaveViewState()
//{
// ViewState["alphacond"] = alphacond;
// return base.SaveViewState();
//}
//protected override void LoadViewState(object savedState)
//{
// if (Page.IsPostBack)
// {
// base.LoadViewState(savedState);
// alphacond = ViewState["alphacond"].ToString();
// }
//}
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowIndex >= 0)
{
// e.Row.Attributes.Add("OnClick", "javascript:" + Page.GetPostBackClientEvent(GridView1, "Select$" + e.Row.RowIndex));
e.Row.Attributes.Add("onmouseover", "this.style.cursor='pointer'");
}
if (keyword == "")
{
if (e.Row.RowType == DataControlRowType.Footer)
{
GridViewRow grv = new GridViewRow(0, 0, DataControlRowType.Pager, DataControlRowState.Normal);
this.GridView1.Controls[0].Controls.Add(grv);
TableCell cell = new TableCell();
grv.Cells.Add(cell);
if (keyword == "")
cell.ColumnSpan = 5;
else
cell.ColumnSpan = 6;
for (int i = 65; i <= (65 + 25); i++)
{
string s = Char.ConvertFromUtf32(i);
if (s == curAlpha)
{
Label lt = new Label();
lt.Text = "[" + s + "]";
lt.Font.Bold = true;
lt.Font.Size = new FontUnit(12);
lt.Style["text-align"] = "middle";
cell.Controls.Add(lt);
}
else
{
LinkButton lb = new LinkButton();
lb.Text = s + " ";
lb.CommandArgument = s;
lb.CommandName = "AlphaPaging";
cell.Controls.Add(lb);
}
}
}
}
}
protected void btnExportToExcel_Click(object sender, EventArgs e)
{
GridView1.Columns[0].Visible = false;
GridView1.AllowPaging = false;
BindData();
GridView1.DataBind();
GridViewExportUtil.Export("ReportResultsPage.xls", this.GridView1);
GridView1.AllowPaging = true;
BindData();
GridView1.Columns[0].Visible = false;
}
private void SaveStates()
{
if (Session["QRY_alpha"] == null) Session["QRY_alpha"] = "";
sqry = Session["QRY_CONDITIONS"].ToString();
origQry = Session["QRY_CONDITIONS"].ToString();
clsUser user = (clsUser)Session["CurrentUser"];
if (user.IsSuperAdmin && sqry == "ALL")
{
sqry = string.Format(" where ifnull(i.activestatus,0) = {0}", ddStatus.SelectedIndex == 0 ? "1" : "0") + Session["QRY_alpha"].ToString();
origQry = string.Format(" where ifnull(i.activestatus,0) = {0}", ddStatus.SelectedIndex == 0 ? "1" : "0");
}
else if (sqry == "ALL")
{
sqry = " where ifnull(i.activestatus,0) = 1 " + Session["QRY_alpha"].ToString();
origQry = " where ifnull(i.activestatus,0) = 1 ";
}
else
{
sqry = Session["QRY_CONDITIONS"].ToString() + Session["QRY_alpha"].ToString();
origQry = Session["QRY_CONDITIONS"].ToString();
}
string tmp = "";
tmp = sqry + "|" +
scolumn + "|" +
keyword + "|" +
GridView1.SelectedIndex.ToString() + "|" +
GridView1.PageIndex.ToString() + "|" +
ddStatus.SelectedIndex.ToString() + "|" +
curAlpha + "|" +
origQry;
Session["PrevState"] = tmp;
}
public void LoadStates()
{
string tmp = (string)Session["PrevState"];
if (tmp == null)
{
return;
}
string[] arr = tmp.Split(new char[] { '|' });
sqry = arr[0];
scolumn = arr[1];
keyword = arr[2];
GridView1.SelectedIndex = Convert.ToInt32(arr[3]);
GridView1.PageIndex = Convert.ToInt32(arr[4]);
ddStatus.SelectedIndex = Convert.ToInt32(arr[5]);
curAlpha = arr[6];
origQry = arr[7];
}
void loadECD(string _idno)
{
SaveStates();
Response.Redirect("~/ECDMain.aspx?i=" + _idno);
}
protected void btnbacksearch_Click(object sender, EventArgs e)
{
Response.Redirect("~/Default.aspx");
}
protected void btnGenerateSF_Click(object sender, EventArgs e)
{
SaveStates();
Response.Redirect("~/ReportViewer.aspx?EmpID=ALL&EmpIDs=" + GetEmpID());
}
private string GetEmpID()
{
string temp = ""; string empIDs = "";
foreach (GridViewRow gRow in GridView1.Rows)
{
temp = GridView1.DataKeys[gRow.RowIndex].Value.ToString();
empIDs = (empIDs == "" ? empIDs : empIDs + ",") + temp;
}
return "(" + empIDs + ")";
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && keyword !="")
e.Row.Cells[5].Text = e.Row.Cells[5].ToString().Replace(keyword,"<span style=//background-color: #FFFF00;//>" + keyword + "</span>");
}
public string HighlightText(string InputTxt)
{
// This function is called whenever text is displayed in the FirstName and LastName
// fields from our database. If we're not searching then just return the original
// input, this speeds things up a bit
if (string.IsNullOrEmpty(keyword))
{
return InputTxt;
}
else
{
// Otherwise create a new regular expression and evaluate the FirstName and
// LastName fields against our search string.
Regex ResultStr = default(Regex);
ResultStr = new Regex(keyword.Replace(" ", "|"), RegexOptions.IgnoreCase);
return ResultStr.Replace(InputTxt, new MatchEvaluator(ReplaceWords));
}
}
public string ReplaceWords(Match m)
{
// This match evaluator returns the found string and adds it a CSS class I defined
// as 'highlight'
return "<span class=highlight>" + m.ToString() + "</span>";
}
//protected void GridView1_RowDataBound1(object sender, GridViewRowEventArgs e)
//{
// if ((e.Row.RowType == DataControlRowType.DataRow))
// {
// //adding an attribut for onclick event on the check box in the hearder and passing the ClientID of the Select All checkbox
// ((LinkButton)e.Row.FindControl("lnkResume")).Attributes.Add("onclick", "javascript:OpenFile('" + GridView1.DataKeys[e.Row.RowIndex].Value + "-" + keyword + "')");
// }
//}
protected void btnGenWord_Click(object sender, EventArgs e)
{
GridView1.AllowPaging = false;
GridViewExportUtil.ExportWord("ReportResultsPage.doc", this.GridView1);
GridView1.AllowPaging = true;
}
protected void GridView1_Sorted(object sender, EventArgs e)
{
BindData();
}
protected void ddStatus_SelectedIndexChanged(object sender, EventArgs e)
{
sqry = sqry + " and i.lastname like '" + curAlpha + "%'";
BindData();
}
}
Please can someone help me. Thanks in advance
You need to rebind the gridview after using the RemoveAt()
GridView1.Columns.RemoveAt(0);
GridView1.DataBind();
When user clicks on export to excel you can disable the delete button, export it and re-enable once exported
GridView1.AutoGenerateDeleteButton = false;
GridView1.DataBind();
GridView1.RenderControl(htmlWrite);
Response.Write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />");

how to extract Paragraph text color from ms word using apache poi

i am using apache POI , is it possible to read text background and foreground color from ms word paragraph
I got the solution
HWPFDocument doc = new HWPFDocument(fs);
WordExtractor we = new WordExtractor(doc);
Range range = doc.getRange();
String[] paragraphs = we.getParagraphText();
for (int i = 0; i < paragraphs.length; i++) {
org.apache.poi.hwpf.usermodel.Paragraph pr = range.getParagraph(i);
System.out.println(pr.getEndOffset());
int j=0;
while (true) {
CharacterRun run = pr.getCharacterRun(j++);
System.out.println("-------------------------------");
System.out.println("Color---"+ run.getColor());
System.out.println("getFontName---"+ run.getFontName());
System.out.println("getFontSize---"+ run.getFontSize());
if( run.getEndOffset()==pr.getEndOffset()){
break;
}
}
}
I found it in :
CharacterRun run = para.getCharacterRun(i)
i should be integer and should be incremented so the code will be as follow :
int c=0;
while (true) {
CharacterRun run = para.getCharacterRun(c++);
int x = run.getPicOffset();
System.out.println("pic offset" + x);
if (run.getEndOffset() == para.getEndOffset()) {
break;
}
}
if (paragraph != null)
{
int numberOfRuns = paragraph.NumCharacterRuns;
for (int runIndex = 0; runIndex < numberOfRuns; runIndex++)
{
CharacterRun run = paragraph.GetCharacterRun(runIndex);
string color = getColor24(run.GetIco24());
}
}
GetColor24 Function to Convert Color in Hex Format for C#
public static String getColor24(int argbValue)
{
if (argbValue == -1)
return "";
int bgrValue = argbValue & 0x00FFFFFF;
int rgbValue = (bgrValue & 0x0000FF) << 16 | (bgrValue & 0x00FF00)
| (bgrValue & 0xFF0000) >> 16;
StringBuilder result = new StringBuilder("#");
String hex = rgbValue.ToString("X");
for (int i = hex.Length; i < 6; i++)
{
result.Append('0');
}
result.Append(hex);
return result.ToString();
}
if you are working on docx(OOXML), you may want to take a look on this:
import java.io.*
import org.apache.poi.xwpf.usermodel.XWPFDocument
fun test(){
try {
val file = File("file.docx")
val fis = FileInputStream(file.absolutePath)
val document = XWPFDocument(fis)
val paragraphs = document.paragraphs
for (para in paragraphs) {
println("-- ("+para.alignment+") " + para.text)
para.runs.forEach { it ->
println(
"text:" + it.text() + " "
+ "(color:" + it.color
+ ",fontFamily:" + it.fontFamily
+ ")"
)
}
}
fis.close()
} catch (e: Exception) {
e.printStackTrace()
}
}

Resources