I have a Excel xlsm file with a few queries.
Currently I open it every day and click on the "Refresh All" command in the "Data" tab. I want this to be done automatically. I wrote a script in python (I'm a newbie in Python).
The problem is that after the data is refreshed and the Excel file has been saved, the refreshed data is not visible (I know that refreshing works because if I prevent to save and close the Excel file, the refreshed data is visible in the file )
The weird thing is that saving also works fine because when I try to modify cell B2 from 'config' it is changed...
Where is the problem?
import win32com.client
import datetime
from datetime import date, timedelta
yesterday = date.today() - timedelta(1)
office = win32com.client.Dispatch("Excel.Application")
wb = office.Workbooks.Open(r'\\server\CC_source.xlsm')
office.DisplayAlerts = True
office.Visible = True
wb.RefreshAll()
sh = wb.Worksheets("config")
sh.Cells(2,2).Value = wczoraj
wb.Close(True)
Maybe someone can recommend another script? For example, Powershell? PHP?
Or an other library for Python3?
Since you requested another script to perform this action, I recommend PowerShell. As a simple test, I created an Excel document, SheetToRefresh.xlsx, which has a data connection to a simple xml file. However, the script below will work for any data source that the Excel document is connected to. I have tested this on my own machine, the data refresh and save persists, as expected.
RefreshExcel.ps1
#Set the file path (can be a network location)
$filePath = "C:\Scripts\SheetToRefresh.xlsx"
#Create the Excel Object
$excelObj = New-Object -ComObject Excel.Application
#Make Excel visible. Set to $false if you want this done in the background
$excelObj.Visible = $true
#Open the workbook
$workBook = $excelObj.Workbooks.Open($filePath)
#Focus on the top row of the "Data" worksheet
#Note: This is only for visibility, it does not affect the data refresh
$workSheet = $workBook.Sheets.Item("Data")
$workSheet.Select()
#Refresh all data in this workbook
$workBook.RefreshAll()
#Save any changes done by the refresh
$workBook.Save()
#Uncomment this line if you want Excel to close on its own
#$excelObj.Quit()
To refresh your query then your pivot, in Excel go to data> queries and connections> right click query for query properties> uncheck the enable background refresh.
Related
I have an XLSM File, where I need to edit some Cell Values with PHP. As I couldn't find a proper library, which can actually edit an xlsm file (most read excel and create a whole new excel file, which in this case would delete the macros inside the excel or even throw too many exceptions), I decided to unzip the xlsm file and directly edit the worksheet xml file by changing the values in the cells:
<c r="K15" s="52">
<v>83221.56</v>
</c>
For example I would change the Value inside the "v" Tag.
As Simple XML doesnt work, because it messes up some namespaces inside the file, I decided to edit it with Regular Expressions.
So far so good - i got the change in the file. But Formulars inside the Excel file, that depend on the cell I just changed the Value in won't recognize my change. When you open the Excel file, it properly shows the correct value, but other cells that use that changed value in their formula won't update.
Does anyone have any idea how to properly change the XML File and keeping the excel in tact?
Thanks!
As I could not figure out a solution in PHP and previous solutions with C++ (Is there a PHP library for XLSM(Excel with Macro) parsing/editing?) where to complicated for me, I found a solution with python, I want to share.
My environment is Ubuntu 16.04, I have Python installed. I have installed https://editpyxl.readthedocs.io/en/latest/
I placed a little script in the same directory as the PHP script, which I call with PHP:
from editpyxl import Workbook
import sys
import logging
logging.basicConfig()
if len(sys.argv) != 4:
print("Three arguments accepted, got " + (str(len(sys.argv) -1)))
print("Argument 1: Sheet name, Argument 2: Cell Identifier, Argument 3: New Value")
sys.exit();
wb = Workbook()
source_filename = r'OriginalFile.xlsm'
wb.open(source_filename)
ws = wb[sys.argv[1]]
ws.cell(sys.argv[2]).value = sys.argv[3]
destination_filename = "NewFile.xlsm"
wb.save(destination_filename)
wb.close()
In PHP I call it via
exec('python excel.py "SheetName" "CellName" "NewValue"')
Seems to be a workaround but it works (especially on Linux) and is very easy to implement. This solution has a performance limitation though. The python script reads, changes the value and saves the excel in each runtime. If you only have some values to change, this might not be a problem but if you plan to edit larger Excel Files with a larger amount of cells to edit, you might write the complete code that edits the xlsm in python.
This code, however, works for me. It edits the Excel and all Formulars/Calculations inside stay fine, also the Macros are still untouched.
I have a php code that is triggered whenever a user clicks a determined button. That code basically creates a new directory and a new Excel File inside that same dir. My goal is to write into that excel file. I have the following code (which is not working, btw):
$filename = 'moldes/VLMOLDES_'.$id.'/Orcamento161.xlsm';
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($filename);
$worksheet = $spreadsheet->getActiveSheet();
$worksheet->getCell('A18')->setValue('3');
Everything but writing in the file is working as expected. When I click the button, it opens a blank page but nothing happens! I've tried a lot of different ways but I'm a noob in phpSpreadSheets. How can I write in a specific cell in that file?
You're missing the following - you need to save the file at the end of your code or the changes won't be reflected in the file.
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, "Xlsx");
$writer->save('moldes/VLMOLDES_'.$id.'/Orcamento161.xlsm');
Also, it may be preferred to use:
$worksheet->setCellValue('A18', '3');
I have an excel template which gets populated with data in one of the sheets. That data is used to update the charts in other sheets of the same excel file. the updated file now gets downloaded automatically. I use laravel-excel to update the data sheet but when i open the file that is downloaded, i find no charts in the sheets.The sheets just become empty. Although, the data gets updated in the other sheets, the charts are getting disappeared. Here's the code that i have written for the same.
Excel::load('maintemplate.xlsx', function($reader) use($data1, $data2)
{
$reader->setIncludeCharts(TRUE);
$sheet = $reader->sheet('Sales');
$sheet->fromArray($data1);
$sheet1 = $reader->sheet('Pivot');
$sheet1->fromArray($data2, null, 'D4', true);
})->download('xlsx');
maintemplate.xlsx is the template file i have which gets populated with data once i run the php code. I have done lot of search for this kind of error on net and found about setIncludeCharts(); Even after setting it to true , i couldn't solve the problem. I even checked the downloaded file with different versions of excel.The problem persists in all of the versions.Please, someone help me with this.
I need to read the data from the .xlsx file when that file is opened without saving it.
The .xlsx file is frequently updating (in every 1 or 2 seconds), so I need last updated data from the file.
<?php
include 'xls/simplexlsx.class.php';
$xlsx = new SimpleXLSX('export_data.xlsx');
$xlxs_value = $xlsx->rows();
echo $xlxs_value;
?>
But when I executed this code, I get data only when the file is last saved, so please help me to read the data without saving the file and it is opened by MS OFFICE.
I have a file in xls format that I need to refresh (use 'refresh all' button in Excel) once a day and then retrieve the data from the pivot table and inset them into the database (MySQL). The file gets data from an external source (retrieve data from sharepoint 2007).
How is the easiest way to do this?
I'm thinking abaout PHP but do I not quite know how you go about it. From what I read PHPExcel does not support this operations.
When you try to use COM I get an error:
Fatal error: in D:\xampp\htdocs\sp\xls\index.php on line 11
And here is a php code:
<?php
// Start Excel
$excel = new COM("Excel.Application") or die ("Could not load Excel.Application");
// Make Excel visible.
$excel->Application->Visible = 1;
// Open workbook
$Workbook = $excel->Workbooks->Open('D:/xampp/htdocs/sp/xls/emails.xls', 'r+') ;
// Refresh all
$Workbook->RefreshAll();
// Save updated excel file out to disk somewhere
$Workbook->SaveAs('D:/xampp/htdocs/sp/xls/emails.xls');
// Close all instances of excel:
$Workbook->Close(false);
unset($Workbook);
$excel->Workbooks->Close();
$excel->Quit();
unset($excel);
?>
I'm using windows 7 and xampp with php 5.5.6
In php.ini I've added this line:
extension=php_com_dotnet.dll
Alternate: is it possible to run *.iqy file generated by sharepoint in php?
I found a workaround to my problem.
Instead, refresh the data by PHP pointed out in a query that collects data during the re-launch of the sheet. To this I added this VBA script save changes and close file.
At the end of the added task scheduler to run the sheet once per day.
The rest of downloading data from Excel using PHPExcel.