how to use poi to find word2003`s table - apache-poi

i use org.apache.poi.poi version 3.17
i want to fine the inclined line in office word2003(doc) tables
for example
enter image description here
i used the XWPFTableRow function
cell.get(index).getCttc().getTcPr().getTcBorders();
to find where is the line in word2007 version (docx)
my code like this :
Rang range = hwpf.getRange();
TableIterator iterator = new TableIterator(range);
while(iterator.hasNext())
{
Table next = iterator.next();
for(int i = 0; i<next.numRows();i++)
{
TableRow row = next.getRow(i);
for(int j =0 ;j<row.numCells();j++)
{
TableCell cell = row.getCell(j);
//now i cant find likeness function to find the line in doc
}
}
}```
but i can`t find likeness function in HWPFDocument
so i need your help
thank you so much

Related

EPPlus corrupt Excel file when having more than 65,530 rows

I'm running into an issue with EPPlus when there are more than 65,530 rows that have a column with a hyperlink. The example below is configured to create 65,530 rows. With this number it will create the Excel file correctly (not corrupt). Once you run it with anything over 65,530, the Excel file will be created but when you open it, Excel will report that is corrupt. Any ideas how to solve this issue?
try
{
int maxRowsToCreate = 65530; //-- no errors will be generated
//int maxRowsToCreate = 65531; //-- error will be generated. The Excel file will be created but will give an error when trying to open it.
string report = string.Format("D:\\temp\\hypelinkIssue-{0}.xlsx", maxRowsToCreate.ToString());
if (File.Exists(report))
{
File.Delete(report);
}
using (ExcelPackage pck = new ExcelPackage(new System.IO.FileInfo(report)))
{
//Add the Content sheet
var ws = pck.Workbook.Worksheets.Add("Catalog");
ws.View.ShowGridLines = true;
var namedStyle = pck.Workbook.Styles.CreateNamedStyle("HyperLink"); //This one is language dependent
namedStyle.Style.Font.UnderLine = true;
namedStyle.Style.Font.Color.SetColor(Color.Blue);
ws.Column(1).Width = 100;
int rowIndex = 0;
for (int i = 0; i < maxRowsToCreate; i++)
{
rowIndex += 1;
string fullFilePath = string.Format("D:\\temp\\{0}", Path.GetRandomFileName());
ws.Cells[rowIndex, 1].StyleName = "HyperLink";
ws.Cells[rowIndex, 1].Hyperlink = new Uri(string.Format(#"file:///{0}", fullFilePath));
ws.Cells[rowIndex, 1].Value = fullFilePath;
}
pck.Save();
}
System.Diagnostics.Process.Start(report);
}
catch (Exception ex)
{
throw ex;
}
The issue occurs when using ".Hyperlink". If instead I use ".Formula" and populate it with the "=HYPERLINK" Excel formula, it works fine. I was able to create 250k records with unique hyperlink using this approach. I did not try more than 250k but hopefully it will work fine.
Thanks for pointing me in the right direction.
/*
This only works with LESS than 65,530 hyperlinks
*/
ws.Cells[rowIndex, 1].StyleName = "HyperLink";
ws.Cells[rowIndex, 1].Hyperlink = new OfficeOpenXml.ExcelHyperLink(fullFilePath, ExcelHyperLink.UriSchemeFile);
ws.Cells[rowIndex, 1].Value = fullFilePath;
/*
This works with more that 65,530 hyperlinks
*/
string cellFormula = string.Format("=HYPERLINK(\"{0}\")", filePath);
ws.Cells[rowIndex, 1].Formula = cellFormula;
This is because Excel limits the amount of unique URLs in a file to 65,530. You should try to insert them as text, instead of a url.
For a possible solution, take a look at this answer.

NPOI set Explicit Column Type Not working properly

I'm using NPOI Excel Library to generate a Excel file, in that Excel file i'm explicitly define column type for Columns like Date,String etc.
Im using the following code to achive this.
var row = sheet.CreateRow(currentNPOIRowIndex++);
for (var colIndex = 0; colIndex < exportData.Columns.Count; colIndex++)
{
ICell cell = null;
cell = row.CreateCell(colIndex);
if (exportData.Columns[colIndex].DataType == typeof(DateTime))
{
if (exportData.Rows[rowIndex][colIndex].ToString() != "")
{
cell.SetCellValue((DateTime)exportData.Rows[rowIndex][colIndex]);
cell.CellStyle = (NPOI.HSSF.UserModel.HSSFCellStyle)book.CreateCellStyle();
cell.CellStyle.DataFormat = book.CreateDataFormat().GetFormat("yyyyMMdd HH:mm:ss");
cell = null;
}
else
cell.SetCellValue(exportData.Rows[rowIndex][colIndex].ToString());
}
else
cell.SetCellValue(exportData.Rows[rowIndex][colIndex].ToString());
}
}
The above code works fine for 42 rows i.e. it correctly set the Column Type,but after 42 rows Column Type doesn't apply.
Any help will be highly appreciated.
you'll required to set default column style if you want to set column format for all cells of that column. Please see the below example from xssf format. Syntax may differ for your hssf format but it will give you idea what you are missing.
I am providing you from my working code. I am using NPOI version 2.2.1.0.
can you comment line //cell = null;
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = (XSSFSheet)workbook.CreateSheet("Template");
XSSFFont defaultFont = (XSSFFont)workbook.CreateFont();
defaultFont.FontHeightInPoints = (short)10;
XSSFCellStyle headerStyle = (XSSFCellStyle)workbook.CreateCellStyle();
headerStyle.WrapText = true;
XSSFCellStyle defaultStyle = (XSSFCellStyle)workbook.CreateCellStyle();
XSSFDataFormat defaultDataFormat = (XSSFDataFormat)workbook.CreateDataFormat();
defaultStyle.SetDataFormat(defaultDataFormat.GetFormat("000-000-0000"));
defaultStyle.FillBackgroundColor = IndexedColors.LightYellow.Index;
defaultStyle.FillForegroundColor = IndexedColors.LightTurquoise.Index;
defaultStyle.SetFont(defaultFont);
var row = sheet.CreateRow(0);
for (int headerCount = 0; headerCount < headers.Count(); headerCount++)
{
row.CreateCell(headerCount).SetCellValue(headers[headerCount]);
row.Cells[headerCount].CellStyle = headerStyle;
sheet.SetDefaultColumnStyle(headerCount, defaultStyle);
}

Comparing excel value with console output using selenium web driver

I am storing excel values in 1st array and console output values in 2nd array. Then I am comparing excel value with console output one by one .I have debug code and it stores value proper in arrays. But it always print "FALSE" even if value matches true.
My latest code is given below :
WebDriver driver = new FirefoxDriver();
driver.get("https://www.google.co.in/?gfe_rd=cr&ei=1YaGVMutHcXN8gf39ID4Aw&gws_rd=ssl#q=what+is+software+testing");
java.util.List<WebElement> links = driver.findElements(By.tagName("h3"));
int sizecount = links.size();
System.out.println(sizecount);
//READING DATA FROM EXCEL FROM 1ST COLUMN
FileInputStream input = new FileInputStream("D:\\sel.xls");
int count=0;
HSSFWorkbook wb = new HSSFWorkbook(input);
HSSFSheet sh = wb.getSheet("sheet1");
String exceldata[] = new String[20];
for (int i=0;i<=sh.getLastRowNum();i++)
{
HSSFRow row = sh.getRow(i);
exceldata[i]= row.getCell(count).toString();
System.out.println(exceldata[i]);
}
String linkdata[] = new String[20];
for(int j=1;j<=links.size()-1;j++)
{
linkdata[j] = links.get(j).getText();
System.out.println(linkdata[j]);
}
for(int k=0;k<links.size()-1;k++)
{
if(exceldata==linkdata)
{
System.out.println("TRUE");
}
else
{
System.out.println("FALSE");
}
}
driver.close();
}
}
Note : I have tried with operator == and .equals both.
I've told you few issues in your program, you can modify your program according to that.
Issue 1
When you are storing the value in exceldata and linkdata array, you are taking different index, exceldata array is storing value from index 0 and linkdata is storing value from index 1, so you need to modify your program something like below:
for(int k=0;k<links.size()-1;k++){
if(exceldata[k].trim().equals(linkdata[k+1].trim())){
System.out.println("TRUE");
}else{
System.out.println("FALSE");
}
}
There was one more issue, I've already told you.
You are good to go now.

How to set Spinner selection by value, using CursorAdapter

I have a spinner I'm populating from the database. I want to choose which item from the list is selected by default. I need to find out what item in the list (CursorAdapter) has the value "Default Away" and set that to the selected value.
Spinner away_team_spinner = (Spinner)findViewById(R.id.away_team_spinner);
DatabaseHelper db = new DatabaseHelper(this);
Cursor team_list = db.getTeams(p_game_level);
startManagingCursor(team_list);
String[] team_name = new String[]{colTeamName};
int[] to = new int[]{android.R.id.text1};
SimpleCursorAdapter adapter =
new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, team_list, team_name, to );
adapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );
away_team_spinner.setAdapter(adapter);
//// HERE IS WHERE MY ERRORS START ////
Log.i("NEW_GAME","Before set arrayadapter");
CursorAdapter adapter_choose = (CursorAdapter)away_team_spinner.getAdapter();
Log.i("NEW_GAME","Before set setSelection");
away_team_spinner.setSelection(adapter_choose.getPosition("Default Away"));
This is the "solution" I found by searching on this web site. However, I cannot use "getPosition" with CursorAdapter object. I tried ArrayAdapter, but then the line after "Before set arrayadapter" comment errors with "android.widget.SimpleCursorAdapter cannot be cast to android.widget.ArrayAdapter". What am I doing wrong? Thanks.
have you thought about running a for loop until you find the position then set the adapter position that way? ill draft up some code then test it, i'm doing something similar
and well this just did the trick, enjoy!
int cpos = 0;
for(int i = 0; i < simpleCursorAdapter.getCount(); i++){
cursor.moveToPosition(i);
String temp = cursor.getString((your column index, an int));
if ( temp.contentEquals(yourString)){
Log.d("TAG", "Found match");
cpos = i;
break;
}
}
spinner.setSelection(cpos);

openxml - inserting a row, moving others

I am using openxml to create an excel report. The openxml operates on a template excel file using named ranges.
The client requires a totals row at the end of the list of rows. Sounds like a reasonable request!!
However, the data table I'm returning from the db can contain any number of rows. Using template rows and 'InsertBeforeSelf', my totals row is getting overridden.
My question is, using openxml, how can I insert rows into the spreadsheet, causing the totals row to be be moved down each time a row is inserted?
Regards ...
Assuming you're using the SDK 2.0, I did something similiar by using this function:
private static Row CreateRow(Row refRow, SheetData sheetData)
{
uint rowIndex = refRow.RowIndex.Value;
uint newRowIndex;
var newRow = (Row)refRow.Clone();
/*IEnumerable<Row> rows = sheetData.Descendants<Row>().Where(r => r.RowIndex.Value >= rowIndex);
foreach (Row row in rows)
{
newRowIndex = System.Convert.ToUInt32(row.RowIndex.Value + 1);
foreach (Cell cell in row.Elements<Cell>())
{
string cellReference = cell.CellReference.Value;
cell.CellReference = new StringValue(cellReference.Replace(row.RowIndex.Value.ToString(), newRowIndex.ToString()));
}
row.RowIndex = new UInt32Value(newRowIndex);
}*/
sheetData.InsertBefore(newRow, refRow);
return newRow;
}
I'm not sure how you were doing it with InsertBeforeSelf before, so maybe this isn't much of an improvement, but this has worked for me. I was thinking you could just use your totals row as the reference row. (The commented out part is for if you had rows after your reference row that you wanted to maintain. I made some modifications, but it mostly comes from this thread: http://social.msdn.microsoft.com/Forums/en-US/oxmlsdk/thread/65c9ca1c-25d4-482d-8eb3-91a3512bb0ac)
Since it returns the new row, you can use that object then to edit the cell values with the data from the database. I hope this is at least somewhat helpful to anyone trying to do this...
[Can someone with more points please put this text as a comment for the M_R_H's Answer.]
The solution that M_R_H gave helped me, but introduces a new bug to the problem. If you use the given CreateRow method as-is, if any of the rows being moved/re-referenced have formulas the CalcChain.xml (in the package) will be broken.
I added the following code to the proposed CreateRow solution. It still doesn't fix the problem, because, I think this code is only fixing the currently-being-copied row reference:
if (cell.CellFormula != null) {
string cellFormula = cell.CellFormula.Text;
cell.CellFormula = new CellFormula(cellFormula.Replace(row.RowIndex.Value.ToString(), newRowIndex.ToString()));
}
What is the proper way to fix/update CalcChain.xml?
PS: SheetData can be gotten from your worksheet as:
worksheet.GetFirstChild<SheetData>();
You have to loop all rows and cells under the inserted row,change its rowindex and cellreference. I guess OpenXml not so smart that help you change index automatically.
static void InsertRow(string sheetName, WorkbookPart wbPart, uint rowIndex)
{
Sheet sheet = wbPart.Workbook.Descendants<Sheet>().Where((s) => s.Name == sheetName).FirstOrDefault();
if (sheet != null)
{
Worksheet ws = ((WorksheetPart)(wbPart.GetPartById(sheet.Id))).Worksheet;
SheetData sheetData = ws.WorksheetPart.Worksheet.GetFirstChild<SheetData>();
Row refRow = GetRow(sheetData, rowIndex);
++rowIndex;
Cell cell1 = new Cell() { CellReference = "A" + rowIndex };
CellValue cellValue1 = new CellValue();
cellValue1.Text = "";
cell1.Append(cellValue1);
Row newRow = new Row()
{
RowIndex = rowIndex
};
newRow.Append(cell1);
for (int i = (int)rowIndex; i <= sheetData.Elements<Row>().Count(); i++)
{
var row = sheetData.Elements<Row>().Where(r => r.RowIndex.Value == i).FirstOrDefault();
row.RowIndex++;
foreach (Cell c in row.Elements<Cell>())
{
string refer = c.CellReference.Value;
int num = Convert.ToInt32(Regex.Replace(refer, #"[^\d]*", ""));
num++;
string letters = Regex.Replace(refer, #"[^A-Z]*", "");
c.CellReference.Value = letters + num;
}
}
sheetData.InsertAfter(newRow, refRow);
//ws.Save();
}
}
static Row GetRow(SheetData wsData, UInt32 rowIndex)
{
var row = wsData.Elements<Row>().
Where(r => r.RowIndex.Value == rowIndex).FirstOrDefault();
if (row == null)
{
row = new Row();
row.RowIndex = rowIndex;
wsData.Append(row);
}
return row;
}
Above solution got from:How to insert the row in exisiting template in open xml. There is a clear explanation might help you a lot.

Resources