How do I select an existing sheet that I know the name of the sheet? I want to append code to a sheet but in different columns. In the code below, I am referring to the wb.creatsheet("Summary") line.
def sql_a = """
SELECT MOPACTIVITY.MOPID FROM MOPUSER.MOPACTIVITY WHERE UPPER(MOPACTIVITY.mopid) = 'JONATHAN MORNINGSTAR'
ORDER BY MOPACTIVITY.MOPID
"""
def date = new Date()
def dts = date.format("yyyy-MM-dd-HH-mm-ss")
File file = new File('X:/CCG/' + dts + ' CCG REPORT.xls')
file.write("")
Workbook wb = new HSSFWorkbook()
try {
Sheet sheet = wb.createSheet("Summary")
sheet.setColumnWidth(0,8.43 * 256)
int rowNum = 0
Row row = sheet.createRow(rowNum)
Cell cellMOPID = row.createCell(0)
cellMOPID.setCellStyle(headerStyle)
cellMOPID.setCellValue("")
db.eachRow(sql_a) {
rowNum++
row = sheet.createRow(rowNum)
cellMOPID = row.createCell(0)
cellMOPID.setCellValue(it.MOPID)
file.append(it.MOPID + "\n")
}
} catch (Exception e) { System.out.println(e.toString()) }
If you look at the JavaDocs for the Workbook interface, you'll see that as well as createSheet(String) there's also a getSheet(String) method. Call that with your existing sheet name, and you'll get the existing sheet to work with
Your code will want to be something like:
Workbook wb = WorkbookFactory.create(new File("input.xls"));
Sheet sheet = wb.getSheet("Summary");
// Read and add to the existing sheet here!
Related
My following 3 line code is used to create one file with sheet1(Year 2019) now would like to execute another page and need to store the result of it in same file as sheet2(Year 2020).
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet("Year 2019");
FileOutputStream fos = new FileOutputStream("C:\\Users\\dp\\Desktop\\MData1_Test_1.xlsx");
Row header_1 = sheet.createRow(rowNum[0]);
rowNum[0] = (rowNum[0] + 1);
header_1.createCell(0).setCellValue("Analytics");
Any help will be appreciated.
You can do something like this:
// open your first file
try (InputStream inp = new FileInputStream(fut.get())) {
Workbook wb = WorkbookFactory.create(inp);
// get sheet by name
Sheet sheet = wb.getSheet("Year 2019");
if (null != sheet) {
// if sheet exists => delete it
int index = wb.getSheetIndex(String name);
wb.removeSheetAt(index);
}
// create new sheet
sheet = wb.createSheet("Year 2019");
// proceed adding data
// row = sheet.createRow(0);
// row.createCell(0).setCellValue("data");
// ...
}
You can repeat these steps as many time as you need to manage as many sheets as you want.
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;
}
}
I’m trying to get the value of column Notes in Sheet 2 and put it to column Notes of Sheet 1. To do that, they should have the same column Company value. When I enter a value in Company (Sheet 2), the code will find if it has the same value in Company (Sheet 1). If the code finds the same value of Company, the value in Notes (Sheet 2) that I enter will automatically put in Notes (Sheet 1). I used the if/else statement in my code but it is not running.
Any help would be greatly appreciated.
Ex:
Sheet 1
enter image description here
Sheet 2
enter image description here
Here's my code :)
function onEdit() {
var sheetId = SpreadsheetApp.openById('1fx59GrC_8WEU5DCM5y2N8YR3PK936RLqZVknQ66WWUA'); //replace with source ID
var sourceSheet = sheetId.getSheetByName('Notes'); //replace with source Sheet tab name
var notesActiveCell = sourceSheet.getActiveCell();
var notesRow = notesActiveCell.getRow();
var notesComp = SpreadsheetApp.getActiveSheet().getRange('B' + notesRow.toString());
var destSheet = sheetId.getSheetByName('Companies'); //replace with destination Sheet tab name
var compActiveCell = destSheet.getActiveCell();
var compRow = compActiveCell.getRow();
var companies = SpreadsheetApp.getActiveSheet().getRange('B' + compRow.toString());
if (notesComp.getValues() == companies.getValues()) {
Logger.log(notesComp.getValues());
var sourceRange = SpreadsheetApp.getActiveSheet().getRange('C' + notesRow.toString()); //assign the range you want to copy
var notesData = sourceRange.getValues();
destSheet.getRange('F' + compRow.toString()).setValues(notesData);
}
}
There are a lot of errors in your code. I'm not a very experienced programmer, but form what you have said I think the script below should give you a good starting point.
Don't forget, you also need to add an onEdit trigger to run the script when you enter a value.
function onEdit(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sourceSheet = ss.getActiveSheet();
var sourceCellRow = sourceSheet.getActiveCell().getRowIndex();
var sourceData = sourceSheet.getRange(sourceCellRow, 1, 1, 2).getValues();
var destSS = SpreadsheetApp.openById('Paste destination Spreadsheet ID here');
var destSheet = destSS.getSheetByName('Companies');
var searchData = destSheet.getRange(1, 1, destSheet.getLastRow()).getValues();
for (var i = 0; i < searchData.length; i ++){
if(searchData[i][0] == sourceData[0][0]){
destSheet.getRange(i + 1, 2).setValue(sourceData[0][1]);
break;
}
}
}
Try using the copyTo(destination)
Copies the data from a range of cells to another range of cells. Both the values and formatting are copied.
// The code below will copy the first 5 columns over to the 6th column.
var sheet = SpreadsheetApp.getActiveSheet();
var rangeToCopy = sheet.getRange(1, 1, sheet.getMaxRows(), 5);
rangeToCopy.copyTo(sheet.getRange(1, 6));
}
I think that will be invaluable inside your onEdit() function.\
You might also want to check this sample from this google forum
function Copy() {
var sss = SpreadsheetApp.openById('spreadsheet_key'); //replace with source ID
var ss = sss.getSheetByName('Source'); //replace with source Sheet tab name
var range = ss.getRange('A2:E6'); //assign the range you want to copy
var data = range.getValues();
var tss = SpreadsheetApp.openById('spreadsheet_key'); //replace with destination ID
var ts = tss.getSheetByName('SavedData'); //replace with destination Sheet tab name
ts.getRange(ts.getLastRow()+1, 1,5,5).setValues(data); //you will need to define the size of the copied data see getRange()
}
When trying to get the Input the data from the Excel Sheet while working with OATS tool, it always gets into the catch block of the function. The below is the script written. Please help us resolve this issue.
public String getInputfromExcel(int argColumnNumber,int argRowNumber)throws Exception
{
String inputExcelName = dataPath+".xlsx";
String cellContent = "12";
try
{
Workbook workbook = Workbook.getWorkbook(new File(inputExcelName));
Sheet sheet = workbook.getSheet(0);
Cell a1 = sheet.getCell(argColumnNumber, argRowNumber);
cellContent = (a1.getContents()).toString();
System.out.println(cellContent.toString());
workbook.close();
}
catch (Exception e)
{
addReport("Getting Input From Excel", "Fail","Exception while reading value from excel sheet");
}
return cellContent;
}
Axel has brought up the point. On a further note, if I remember correctly, the function sheet.getCell(arg1, arg2) has first argument as rowNumber and 2nd as columnNumber (both the values are 0 based index).
Its old quetion....but just posting answer it might be helpful for someone needy.
In Oracle Application Testing Suite. NO NEED of external JARs to read/write data.
You can enable DataTable module in the tool
Complete explanation given here, http://www.testinghive.com/how-to-read-write-excel-in-oats/
//Define Sheet name to be read, and provide comma seperated to read multiple sheets
String sheetName = "Sheet1";
//Mention excel sheet path
String strFile= "C:\\Demo\\test.xls";
//Defined array list to add Sheets to read
List sheetList = new ArrayList();
sheetList.add(sheetName);
// Iports Sheet1
datatable.importSheets(strFile, sheetList, true, true);
//get rowcount
info("Total rows :"+datatable.getRowCount());
int rowcount=datatable.getRowCount();
//Loop to read all rows
for (int i=0;i<rowcount;i++)
{
//Set current row fromw here you need to start reading, in this case start from first row
datatable.setCurrentRow(sheetName, i);
String strCompany=(String) datatable.getValue(sheetName,i,"Company");
String strEmpFName=(String) datatable.getValue(sheetName,i,"FirstName");
String strEmpLName=(String) datatable.getValue(sheetName,i,"LastName");
String strEmpID=(String) datatable.getValue(sheetName,i,"EmpID");
String strLocation=(String) datatable.getValue(sheetName,i,"Location");
//prints first name and last name
System.out.println("First Name : "+strEmpFName+", Last Name : "+strEmpLName);
//Sets ACTIVE column in excel sheet to Y
String strActive="Y";
datatable.setValue(sheetName, i, datatable.getColumn(sheetName, datatable.getColumnIndex("Active")), strActive);
}
//Updates sheet with updated values ie ACTIVE column sets to Y
datatable.exportToExcel("C:\\Demo\\test1.xlsx");
I want to import Excel data to Microsoft Dynamics Ax. I've used this code from this site:
http://axpedia.blogspot.com.tr/2013/02/import-from-excel-file-using-x-in-ax.html
but when i try to run i get this error:
SysExcellworksheet could not start (C)\Classes\SysExcellWorksheets\cells(C)\Jobs\ProductType (line 35)
I am newbie Can you help me about this?
static void ProductType(Args _args)
{
SysExcelApplication application;
SysExcelWorkbooks workbooks;
SysExcelWorkbook workbook;
SysExcelWorksheets worksheets;
SysExcelWorksheet worksheet;
SysExcelCells cells;
COMVariantType type;
Name name;
FileName filename;
ProductType productType;
int row;
int _productTypeId;
str _productType;
str _description;
;
application = SysExcelApplication::construct();
workbooks = application.workbooks();
//specify the file path that you want to read
filename = "Path\\filename.xlsx";
try
{
workbooks.open(filename);
}
catch (Exception::Error)
{
throw error("File cannot be opened.");
}
workbook = workbooks.item(1);
worksheets = workbook.worksheets();
worksheet = worksheets.itemFromNum(4); //Here 3 is the worksheet Number
cells = worksheet.cells();
do
{
row++;
_productTypeId = any2int(cells.item(row, 1).value().toString());
_productType = cells.item(row, 2).value().bStr();
_description = cells.item(row, 3).value().bStr();
productType.ID = _productTypeId;
productType.ProductType = _productType;
productType.Description = _description;
productType.insert();
type = cells.item(row+1, 1).value().variantType();
}
while (type != COMVariantType::VT_EMPTY);
application.quit();
}
You probably translated the error, the exact error when I test this is:
SysExcelWorksheet object not initialized.
This is probably because on the following line you are trying to retrieve the 4th worksheet of the excel, but your excel file has less:
worksheet = worksheets.itemFromNum(4);
If your data is on the first worksheet, use '1' instead of '4':
worksheet = worksheets.itemFromNum(1);