divide excel sheet based on spesific cell values - java

i have a data sheet in excel about 950000 row with 7 col.and i want to divide it based on V5 col data. V5 holds data for time in seconds into one hour so i need to divide the data into sheets each sheet contains all value related to one minute and so on until finish splitting
if any help in do it with micro VBA thats will be good.
this is what i could do in VBA
Sub SPLIT()
Dim ws1, ws2 As Worksheet
Dim row2 As Integer
Dim rw As Range
Dim dv, fv As Variant
Set ws1 = Sheets("sheet1")
Set ws2 = Sheets.Add
row2 = 1
For Each rw In ws1.Rows
If rw.Cells(1, 5).Value2 = 00:00:59 Then " and so on until i divide each minute data rows alone"
Exit For
End If

So I've put something together for you that will get you started. You'll likely have to adjust the code for the exact time bounds that fit your requirement (which will be a good learning oppurtunity!). Note that you can take an approach of setting these bounds as either fixed or variable (i.e.: increments of minutes/seconds/hours, or the fixed bounds I have now)
To set this up you'll need three sheets in your workpaper named (1) Hours, (2) Minutes, and (3) Seconds.
As the code is set up the rows get sorted and placed into bounds depending on if it's under one minute, under one hour, or greater than one hour.
Take a stab at adjusting the code to your exact requirements and if you have any questions feel free to let me know!
Function Last_Row(Sheet_Name As String)
Last_Row = Sheets(Sheet_Name).Range("A" & Sheets(Sheet_Name).Rows.Count).End(xlUp).Row
End Function
Sub AllocateSheet()
Dim Cell As Variant
Dim Cell_Range As Range
Set Cell_Range = Range("E2:E990000")
Seperator_Second = TimeValue("00:00:01")
Seperator_Minute = TimeValue("00:01:00")
Seperator_Hour = TimeValue("01:00:00")
For Each Cell In Cell_Range
If Cell.Value >= Seperator_Hour Then
Rows(Cell.Row).Copy Destination:=Sheets("Hours").Rows(Last_Row("Hours") + 1)
ElseIf Cell.Value <= Seperator_Hour And Cell.Value >= Seperator_Minute Then
Rows(Cell.Row).Copy Destination:=Sheets("Minutes").Rows(Last_Row("Minutes") + 1)
ElseIf Cell.Value <= Seperator_Minute And Cell.Value >= Seperator_Second Then
Rows(Cell.Row).Copy Destination:=Sheets("Seconds").Rows(Last_Row("Seconds") + 1)
End If
Next Cell
End Sub

I reach into deviding minutes uisng this code any help in edit this code so i can divide the total rows in the sheet about 1000000 row also the code make the loop only to 60000 row in E colunm. I dont know why it just took from 1 to 6000 E1:E6000 and make a loop on 60000 row any help. also how i can craete new sheet to
paste to it inside code.
Option Explicit
Sub Test()
ti=TimeValue("00:00:00")
Dim Cell As Range
With Sheets(1)
For Each Cell In .Range("E1:E6000" & .Cells(.Rows.Count, "E").End(xlUp).Row)
If Cell.Value <= ti Then
.Rows(Cell.Row).Copy Destination:=Sheets("first minute").Rows(Cell.Row)
End If
Next Cell
End With
End Sub

Related

Apache POI - Allow calculation with time strings

I have an excel sheet which contains some time values. These values are Durations formatted to Strings. When I try to do a sum on those values I get a 0 as result since Excel can't do sums on Strings. When I hit the enter button in the formula bar it does become a time so I the sum works. How do I change the value of the cell from a String to a time value? I already have the date format set up as [hh:mm] with a DateFormat
I start with an amount of time converted into seconds which I convert into a Duration
Duration clockedDuration = Duration.ofSeconds(clockedSeconds)
Then I format the Duration to a String using DurationFormatUtils
DurationFormatUtils.formatDuration(duration.toMillis(), "HH:mm", true)
Then I set the cell value to the String that was just made
c.setCellValue(clockedDuration)
I then set the CellStyle to one that has a DataFormat that's set up as [hh]:mm
Lastly I make a sum of all the values in that particular column (B in this instance)
c = r.createCell(i++)
c.setCellFormula("SUM(B2:B" + lastRow +")")
c.setCellType(Cell.CELL_TYPE_FORMULA)
This is the sheet before I hit the enter button on the first value in the row (09:52)
This is the sheet after I've hit the enter button in the formula bar
I fixed it by dividing the seconds by 86400 to get a decimal value and then use [hh]:mm as the data format.
c.setCellValue(clockedSeconds / 86400) // 24(hours) * 60(minutes) * 60(seconds) = 86400
Just a hunch: you mentioned to actually use formulas, and if you are hitting enter on the sheet "the sum works". Applying formulas is a two-liner, in addition to set the "value", you also need to format the cell type as being a formula:
XSSFRow row = worksheet.getRow(rowIndex);
XSSFCell cell = row.getCell(cellIndex);
cell.setCellType(XSSFCell.CELL_TYPE_FORMULA);
cell.setCellFormula("sum(start:end)");
Edit: You also will want to make sure to use the XSSF-Classes

iText formatting tables

I'm generating a PDF document (for those who have seen his before, yes still) using the iText5 library. Compliments to Bruno Lowagie; I've found it to be a really great API!
However, part of my task is to format some phrases. I used a nested PdfPTable to format the data, but I'm getting bizarre spacing issues. Here is an example of the problem I'm facing:
As you can see, rows with only a couple of phrases in them tend to have huge gaps in between them. I can understand why this is happening; the rows above are stretching the table. Is there a way to only make the table as big as it needs to be, and no larger?
Code
Generating the prices collection
I'm creating the prices with this snippet:
Paragraph pricePara = new Paragraph();
pricePara.add(price);
pricePara.add(generateBreakLine());
pricePara.add(time);
pricePara.add(generateBreakLine());
allPrices.add(pricePara);
where generateBreakLine() returns an empty Paragraph object.
Adding them into the cell
I add them into the cell with the following snippet:
// 5 is just the amount of prices we can fit on one line.
PdfPTable pricesCellValue = new PdfPTable(elements.size() > 5 ? 5 : elements.size());
// Make it appear that the prices are just horizontal, as opposed to in a table.
pricesCellValue.getDefaultCell().setBorder(PdfPCell.NO_BORDER);
// Cycle through each price. Add to cell. Add cell to the table.
for (com.lowagie.text.Element elem : elements) {
PdfPCell cell = new PdfPCell((Paragraph) elem);
cell.setBorder(PdfPCell.NO_BORDER);
cell.setPadding(2);
pricesCellValue.addCell(cell);
}
return pricesCellValue;
The above snippet, I believe, is where I can make sure the table is only as wide as it needs to be, as opposed to filling up all the space around it. How would I go about doing that?
Solved
Found a simple way of fixing it. In stead of changing the amount of columns based on the number of prices, I make sure the column number is always 5, and then append empty cells on:
if(elements.size() < 5)
{
int diff = 5 - elements.size();
for(int x = 0; x < diff; x++)
{
pricesCellValue.addCell(new Paragraph(" "));
}
}

Writing to a particular cell location using Apache POI Excel

If I've got an list of parameters 'x,y,z' that aren't sorted, is there a straightforward way to write them to particular cells in an excel document created with POI, as though the first two parameters are X and Y coordinates?
For example, I have rows like:
10,4,100
Is it possible to write the value '100' in the cell at the 10th row, 4th column?
Looking at the documentation, it looks straightforward to iterate values into the next row, but I can't see any way of creating a fixed number of rows and columns and writing particular values to only certain cells.
Any advice or suggestions would be appreciated, thanks!
Sure, it's very easy, just remember that POI is 0 based not 1 based in addressing. Assuming you want to write to the 10th row, 4th column, you'd do something like
Row r = sheet.getRow(9); // 10-1
if (r == null) {
// First cell in the row, create
r = sheet.createRow(9);
}
Cell c = r.getCell(3); // 4-1
if (c == null) {
// New cell
c = r.createCell(3, Cell.CELL_TYPE_NUMERIC);
}
c.setCellValue(100);

getting the changed lines jtextarea

I am doing a text editor which needs custom validation. Since, the content is very large i thought of validating only the lines which are changed or added. The validation errors are shown by the line numbers, like "Line: 10 cannot exceed 15 chars"
For single lines, every time the user changes iam validating the current line, keeping the row number as reference. - solved
The user can copy text and paste - multiple lines. for this, thought of getSelectionStart and getSelectionEnd. Is there a way of getting the row numbers from getSelectionStart and getSelectionEnd, so i can get starting row and ending row?
After some exprements i thought selecting the lines which are visible will solve my above statated No. 2 problem.
Rectangle would solve in getting the x, y cordinates of viewable region and wrote the code, i think i am almost finished. But, i am not getting the end row number correctly,
[code]
//editor is jtextarea
Rectangle r = editor.getVisibleRect();
Point top = new Point(r.x, r.y);
Point bottom = new Point(r.x, r.y + r.height);
int startRow = editor.viewToModel(top); /* this is working. it shows 0 at initial, then after the line reaches the end and when the scrollbar gets displayed, it shows the numbers correctly, 1,2,3...*/
int endRow = editor.viewToModel(bottom); /* this is not working, when we type, it is taking column numbers */
editorLineNo.setText(" START ROW " + startRow + " END ROW" + endRow);
[/code]
What is needed is, start row number and end row number from the viewable area of jtextarea
Is there a way of getting the row numbers ...
Element root = textArea.getDocument().getDefaultRootElement();
int row = root.getElementIndex( selectionStart ) + 1;
Utilities.getRowStart() / getRowEnd() passing the offsets.

retrieve boolean values from jtable

in my Jtable I have a column with boolean values displayed as checkbox.
I can retrive the value cell only when the value is true, when values i false I can't read the values.
I write my code:
int row = jTMezziInt.getRowCount();
int h=0;
while (h<=row){
chk= ((Boolean)jTMezziInt.getValueAt(h, 6)).booleanValue();
//if chk is true I can read;
// if chk is false the execution stopped at the chk assignement;
if (chk)
((DefaultTableModel )this.jTMezziInt.getModel()).removeRow(h);
row = jTMezziInt.getRowCount();
h=h+1;
}
TableColumn Selez = jTMezziInt.getColumnModel().getColumn(6);
}
For define the table I had used netbeas with table editor.
Thanks everybody for help;
There are one of two possible issues here from what I can see. The most likely issue is that you start with h = 0 and then end with h = row (since your while loop iterates while h <= row).
Say for example you have 3 rows in your table. This loop will now run for h = 0, h = 1, h = 2 and h = 3, i.e. it runs 4 times but you only have 3 rows (indexed 0, 1 and 2 there is no row with index 3). This would cause a null pointer exception on its final iteration. Is this the behaviour you are seeing?
To sort it out just make your while loop condition h < row, not h <= row. If this does not work then let me know and we can discuss the other possible issue.
Another issue is that you still increment h even if the row you are checking is deleted. If we are checking row 1 and then delete row 1 then row 2 will become row 1, so we need to recheck this new row 1. So you should only increment h if the current row you are checking is not deleted.
Finally, as an aside, note that if you are using one of the later JDKs there is no need to call booleanValue() (this is called unnecessary unboxing). This will be done automtically for you. So you can change the following:
chk= ((Boolean)jTMezziInt.getValueAt(h, 6)).booleanValue();
to:
chk= (Boolean)jTMezziInt.getValueAt(h, 6);
It's just neater and better style.

Categories