poi has a implicitly max row number - apache-poi

I used poi 3.12 to create excel, and found a phenomenon, that is explicitly created 30000 rows, but open the generated excel, only have 27239 rows, and there is no error output. So it seems poi have set a default max row number--27239. But I tried track source code, cannot find some variable like max rows. The code is
InputStream is = new FileInputStream(srcFile);
POIFSFileSystem pOIFSFileSystem=new POIFSFileSystem(is);
HSSFWorkbook srcWorkbook = new HSSFWorkbook(pOIFSFileSystem);
buildBusiData(srcWorkbook);
FileOutputStream fileOutputStream = new FileOutputStream(desFile);
srcWorkbook.write(fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
So how is this?

I have found the reason, that is the source file(template) only have 27239 rows
#source file
cat coupon_code_box.csv | wc -l
27240
#
head coupon_code_box.csv -n 3
table header here
" "," "," "," "," "," "," "," "," "
" "," "," "," "," "," "," "," "," "
and in my code does not create new row explicitly, so if row number greater than 27239, it'll ignore it.
Row row = sheet.getRow(rowIndex);
if(row!=null){
Cell cell = row.getCell(celIndex);
cell.setCellValue(fillVal);
}
Now my solution is
Row row = sheet.getRow(rowIndex);
if(row==null){
row=sheet.createRow(rowIndex); //explicitly create one new row
}
if(row!=null){
Cell cell = row.getCell(celIndex);
if(cell==null)
cell = row.createCell(celIndex); //explicitly create one new cell
cell.setCellValue(fillVal);
}

Related

Python -- Adding string to clipboard that will paste to Excel in proper format (i.e., separated into rows/columns)

I've seen a few answers to this problem, but in VBA and C#---nothing in python.
In python 3, I'm trying to do the following:
Assign a variable a string of values with appropriate "excel" format
Have this variable then copied to the clipboard
Then the user should be able to manually CTRL+V (paste) this string into excel and have it separate into the correct row/column placements.
I'm using both tkinter and openpyxl for my project and through testing I've gotten some results, but it is not what I want. The closest that I've gotten is below.
# If I first go into excel,
# and copy a few columns within a single row with different data in them,
# then I run the following code:
import tkinter as tk
root = tk.Tk()
paste = root.clipboard_get()
print(paste)
# Then I manually copy the print output to the clipboard,
# and then go back to excel and paste,
# excel gives the following warning message:
# "The data you're pasting isn't the same size as your selection. do you want to paste anyways?"
# And after pressing OK, it seems as though the data is pasted properly.
This is OK, and the print(paste) string might help me create the appropriate format for the initial variable of strings that I want to generate, but I need a solution that will not cause Excel to make this warning sign pop up every time.
If anyone can provide some insight into this, I would greatly appreciate it. Also, the solution needs to be via python not through modifications to Excel. Secondly, the solution is not about appending/writing the data directly to Excel (via Openpyxl, etc) but about getting the data to the clipboard in the appropriate format (I'm using Excel 2016).
Thanks!!
Edit:
I have also tried using the "ctypes solution" presented here by user kichik.
To make this solution easier to work with, I downloaded an app called "InsideClipboard" which lets me easily see the format ID of each types of formats that the clipboard "copies" data in.
Using kichik's ctype solution, I checked to see if manually copying the print output of the different formats stored in the clipboard would let me manually CTRL+V to Excel in the original format, but this failed. The original "copy" was of multiple columns of strings in a single rows of strings from Excel, and the manual "paste" of the individual formats back into excel kept all the strings into a single cell (with the exception of HTML Format that created multiple rows of data--also wrong). The different formats included CF_LOCALE (16), CF_TEXT (1), CF_OEMTEXT (7), CF_UNICODETEXT (13), AND HTML Format (49384).
So, still: no solution.
Edit2:
I realized that I could create strings in python with actual tabs pressed in between the string, instead of using \t, and it worked to create a single string that would place the data into different columns of a single row when pasted into Excel.
Also, I realized that if I CTRL+V directly into Excel (not on the Row heading), on the actual row in which I want to paste the data, I no longer get the Excel "warning message". So, using this work around might work. If no one has any input, then this simple approach might be good enough.
However, I would like to be able to simply click on the row heading instead of the first relevant row cell to paste the data without the Excel warning popup. Ideas are still welcome, and it would be best to have it all done via python (without modifications to Excel as the app may be run on different Windows OS PCs).
So: possible simple solution, but not perfect.
Edit3:
So I've worked out a solution based on Edit2. The Excel "warning" popup still happens if Excel is opened as an app on the working computer; however, if the Excel file is opened and editable via an online processor, then the user can highlight the row heading and paste without generating the Excel "warning" popup. This works in my specific case, although the better solution would be to have the copied data not generate the Excel "warning" popup in any situation. Regardless, if no one knows how to prevent the Excel warning popup through python alone, then I can still work with this method.
Here's my solution (note that the spaces in the long string are actually 'tabs'):
import pyperclip
# t variables are defined prior to the below code
# note: the " " parts in the data string are actually tabs
data = t1 + " " + t2 + " " + " " + t3 + " " + t4 + " " + t5 + " " + t6 + " " + t7 + " " + " " + "t8" + " " + " " + " " + " " + " " + " " + t9 + " " + t10 + " " + t11 + " " + t12 + " " + " " + " " + " " + " " + " " + t13
pyperclip.copy(data)
print("clipboard:", data)
# now manually pressing CTRL+V while inside Excel (online processor) will
# paste the various t variables in the appropriate cells designated by
# the " " tabs in between. Of note, this works for columns of a single
# row as I didn't need multiple rows of data for my task.
Below is code to create a 5 row by 3 column grid of Entries in tkinter. Pressing the copy button copies the content of the Entries as a tab / newline separated string to the clipboard which can then be pasted into excel.
import tkinter as tk
from tkinter import ttk
ROWS = 5
COLS = 3
root = tk.Tk()
rows = [] # Container for Entry widgets.
# Create and grid the Entry widgets.
for row in range( ROWS ):
temp = []
for col in range( COLS ):
temp.append( ttk.Entry(root, width = 10 ))
temp[-1].grid( row = row, column = col )
rows.append( temp )
def entries_to_lists( rows ):
list_out = []
for row in rows:
temp = []
for col in row:
temp.append( col.get() )
list_out.append( temp )
return list_out
def string_out( rows ):
""" Prepares a '\t', '\n' separated string to send to the clipboard. """
out = []
for row in rows:
out.append( '\t'.join( row )) # Use '\t' (tab) as column seperator.
return '\n'.join(out) # Use '\n' (newline) as row seperator.
def do_copy():
data = entries_to_lists( rows )
root.clipboard_clear()
root.clipboard_append( string_out( data )) # Paste string to the clipboard
root.update() # The string stays on the clipboard after the window is closed
ttk.Button( text = " Copy ", command= do_copy ).grid( column = 1 )
# Button to trigger the copy action.
root.title("Copy to Excel Test")
root.geometry("400x200+10+10")
root.mainloop()
This copied into Excel 2013 in Windows 10 with no warning messages.
string_out will generate a suitable string from any list of lists of strings, a 2d list.

how to fill excel sheet from database using Aspose

how to fill excel sheet from database using Aspose total or Aspose Cells
giving an Excel template that might contain formulas which should be keept active after filling the Excel document.
Well, to import or merge data from your data source to Excel files, we have two options and you may try any one for your needs.
e.g
1) Use Smart Markers feature provided by Aspose.Cells. So, you may create a designer template file inserting the markers into the cells in the sheet(s), you may also format the cells accordingly for your needs. For example, you may create reports for your database tables related to different sets of data or as per your desired records etc. Smart Markers are processed based on your desired dataset/resultset that might be the result of the query or stored procedure, so you may specify or write the query to be processed by using your own code with e.g ADO.NET APIs and get the data to be filled into the DataTable or variables/Array. When the markers are processed, data is inserted into the cells in place of your pasted markers in the designer file's sheets, see the document for your complete reference.
2) Use data importing options from different data sources provided by Aspose.Cells. For example, you may use Cells.ImportDataTable() method to import the data table to fill the worksheet in the Workbook. Please see the document for your complete reference.
PS. I am working as Support developer/ Evangelist at Aspose.
after creating a folder in your project where you will have the Excel file that you want to generate and adding the Aspose.Total to your using statments. Create the following method to generate the excel
file:
protected void CurrentExcel_Click(object sender, EventArgs e){
//getting the items that will fill the cells(should be different
//than below)
Items searchItems = new SearchItems();
searchItems.ProjectStatusIDs = new List<int> { 24721 };
List<CurrentRecord> resultsRecords =
YourEntity.GetCurrentRecords().OrderBy(c => c.LOCATION).ToList();
// the template Excel file that you will fill
string fileName = "currents_list_Excel_Shortened.xlsx";
//define a workbook that will help you access Excel file cells
Workbook wb = new Workbook(Server.MapPath(string.Format(#"
{0}/{1}", "~/Templates/", fileName)));
//adding worksheet that will be filled
wb.Worksheets.Add(SheetType.Worksheet);
Worksheet ws = wb.Worksheets[0];
ws.Name = "Current Shortened";
try
{
Aspose.Cells.Cells wsCells = ws.Cells;
int x = 8;
foreach (CurrentRecord mwa in resultsRecords)
{
Cell Cell1 = ws.Cells[x, 0];
Cell Cell2 = ws.Cells[x, 1];
Cell Cell3 = ws.Cells[x, 2];
Cell Cell4 = ws.Cells[x, 3];
Cell Cell5 = ws.Cells[x, 4];
Cell Cell6 = ws.Cells[x, 5];
Cell Cell7 = ws.Cells[x, 6];
Cell Cell8 = ws.Cells[x, 7];
Cell Cell9 = ws.Cells[x, 8];
Cell Cell10 = ws.Cells[x, 9];
Cell Cell11 = ws.Cells[x, 10];
Cell Cell12 = ws.Cells[x, 11];
Cell Cell13 = ws.Cells[x, 12];
Cell Cell14 = ws.Cells[x, 13];
// here filling your object properties to the cells which
//should be different than the one below
Cell1.PutValue(mwa.ID + "-" +
mwa.LOCATION);
Cell2.PutValue(mwa.number);
Cell3.PutValue(mwa.Rate + " " + mwa.POSTMILE + " " +
mwa.POSTMILE_KPList);
Cell4.PutValue(mwa.PROJECT_LOCATION_TYPE);
Cell5.PutValue(mwa.RELName.Split(' ')[0] + "/" +
mwa.RECell);
if (mwa.COMPANY_NAME != "")
{
Cell6.PutValue(mwa.COMPANY_NAME.IndexOf('-') != -1 ?
mwa.COMPANY_NAME.Split(' ')[0] :
mwa.COMPANY_NAME.Split(' ')[0] + ' ' +
mwa.COMPANY_NAME.Split(' ')[1]);
}
Cell7.PutValue(mwa.PROJECT_STATUS);
Cell8.PutValue(mwa.PROJECT_LOCATION_WORKING_DAYS);
Cell9.PutValue(mwa.PROJECT_STATUS_PE_DAYS);
Cell10.PutValue(mwa.PROJECT_STATUS_WORK_SUSPENDED == true
? "Yes" : "NO");
Cell11.PutValue(string.Format("{0:0.######}",
mwa.PROJECT_STATUS_WORK_COMPLETED) + "/" +
string.Format("{0:0.######}",
mwa.PROJECT_STATUS_TIME_COMPLETED));
Cell12.PutValue(mwa.M600 != null ? string.Format("{0:d}",
mwa.M600) : "TBD");
Cell13.PutValue(mwa.Contractual != null ? string.Format("
{0:d}", mwa.Contractual) : "TBD");
Cell14.PutValue(mwa.PROJECT_STATUS_UPDATED_EST_COMPLETION
!= null ? string.Format("{0:d}",
mwa.PROJECT_STATUS_UPDATED_EST_COMPLETION) : "TBD");
x++;
}
wb.Save(HttpContext.Current.Response, fileName,
Aspose.Cells.ContentDisposition.Attachment, new
XlsSaveOptions(Aspose.Cells.SaveFormat.Xlsx));
}
catch(Exception ex)
{
throw;
}
}

How to convert part of a cell value to bold

I have the below VBA code and A and B are holding some strings. I want to concatenate these values with some other strings and store the result in a different cell, but I want only the strings in A and B to be formatted as bold and the rest as normal text.
Set A = Worksheets("Mapping").Cells(rowNumber, columnNumber)
Set B = Worksheets("Mapping").Cells(rowNumber, 3)
' E.g.: A="currency", B="Small Int"
Worksheets("TestCases").Cells(i, 2) = "Verify the column " & A & " has same Data type " & B & " in code as well as Requirement document"
Expected output:
Verify the column currency has same Data type Small Int in code as well as Requirement document
Note: The values of A and B keep changing, so we cannot use the Characters() function.
Any help will be highly appreciated.
You can use the Characters() method - you just need to keep track of the length of the substrings. Personally, I would store the static strings in variables so that I can change them later without having to recalculate the indexes by hand:
' Untested
Set A = Worksheets("Mapping").Cells(rowNumber, columnNumber)
Set B = Worksheets("Mapping").Cells(rowNumber, 3)
Dim S1 = "Verify the column "
Dim S2 = " has same Data type "
Dim S3 = " in code as well as Requirement document"
With Worksheets("TestCases").Cells(i, 2)
.Value = S1 & A & S2 & B & S3
.Characters(Len(S1), Len(A)).Font.Bold
.Characters(Len(S1)+Len(A)+Len(S2), Len(B)).Font.Bold
End With
The function to change the font style is:
[Cells/Cell range].Font.FontStyle = "Bold"
Therefore something like might work:
Worksheets("Mapping").Cells(rowNumber, columnNumber).Font.FontStyle = "Bold"
You can also make things have underlines, strikethroughs etc... I found this really helpful blog post which goes through everything you should need to know:
http://software-solutions-online.com/excel-vba-formating-cells-and-ranges/#Jump4
I think you should have searched for this information yourself... Nevertheless this is the code that you should use to convert some cell data to bold:
Worksheets("Mapping").Cells(rowNumber, columnNumber).Font.Bold = True

Data Filter SAS VBA

data.Filter = "(Dec = 'Okay' AND no = '001' AND date >=" &
Sheets("parameter").range("A1") & ")" & _"or (Dec = 'Okay' AND
(criteria = 'TOM1' OR criteria = 'TOM2' OR criteria = 'TOM3') AND
date >=" & Sheets("parameter").range("A1") & ")"
Why does it show a run time error? I believe the problem starts from the filter consisting "criteria". How do I make things right?
NOTE: By adding additional line is no longer allowed as the maximum number of line is at 24, and i already exceeded it.
It is probably because of the date values you're passing in from Sheets("parameter").range("A1").
Assuming you're passing in a value from A1 of 20JAN2015 for example, you could try something along the lines of the below:
data.Filter = "(Dec = 'Okay' AND no = '001' AND date >='" &
Sheets("parameter").range("A1") & "'d)" & "or (Dec = 'Okay' AND
(criteria = 'TOM1' OR criteria = 'TOM2' OR criteria = 'TOM3') AND
date >='" & Sheets("parameter").range("A1") & "'d)"
This would give:
(Dec = 'Okay' AND no = '001' AND date >='20JAN2015'd) or (Dec = 'Okay' AND
(criteria = 'TOM1' OR criteria = 'TOM2' OR criteria = 'TOM3') AND
date >='20JAN2015'd)
Compare this with:
data _null_ ;
datetxt='20JAN2015' ;
datenum='20JAN2015'd ;
put "Date as text " datetxt= ;
put "Date as SAS date " datenum= ;
run ;

read excel to datatable with intermixed data

I want to read excel to datatable.But I have a problem.I have a column "ALS" which contains mixed type data.When I read excel to dataset "Kukla" is DbNul value instead.I cant read such columns all datas
example, column data:
2000
Kukla
2000
1000
1000
String sConnectionString =
"Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + "C:\\DrcrUpload\\" + filePath + ";" +
"Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\"";
OleDbConnection objConn;
objConn = new OleDbConnection(sConnectionString);
OleDbCommand objCmdSelect = new OleDbCommand("SELECT * FROM" + "[" + name + "]", objConn);
objAdapter1.Fill(objDataset1);
You have a few options
1.Change the registry setting TypeGuessRows = 0
2.List all possible type variations in the first 8 rows as 'dummy data' (eg memo fields/nchar(max)/ errors #N/A etc)
This thread may help also Link

Resources