XLSXWriter and Excel “=SORT()” Function? - excel

I learned in this SO post about using XLSXWriter to add a =FILTER() function to a workbook.
Now I'm trying to add a =SORT() function. So far I have tried this:
worksheet.write_array_formula('H2', '=_xlfn._xlws.SORT(A2:F16, 6, -1)')
...but SORT doesn't appear to be an array formula. I have also tried this:
worksheet.write_formula('H2', '=_xlfn.SORT(A2:F16, 6, -1)')
worksheet.write_formula('H2', '=_xlfn._xlws.SORT(A2:F16, 6, -1)')
The formula appears in the worksheet, but instead of being:
=SORT(A2:F16, 6, -1)
...it appears as:
=#SORT(A2:F16, 6, -1)
How can I correct this?

This is similar to the other answer that you linked to and your first attempt is almost correct. I think you just need to specify a range that the range formula applies to like this:
import xlsxwriter
workbook = xlsxwriter.Workbook('test.xlsx')
worksheet = workbook.add_worksheet()
worksheet.write_array_formula('H2:M16',
'=_xlfn._xlws.SORT(A2:F16, 6, -1)')
workbook.close()
Output:

Related

Hiding #N/A or empty cells from an excel chart produced by xlsxwriter

Essentially I am generating a number of charts with xlsxwriter and trying to ensure gaps appear in the chart where I have #N/A's. Unfortunately it is not possible unless the show #N/A as empty cell setting is selected (I dont believe it is a supported feature as it is relatively new for excel).
I am currently using the following code to produce the above:
from xlsxwriter.workbook import Workbook
workbook = Workbook('chart.xlsx')
worksheet = workbook.add_worksheet()
bold = workbook.add_format({'bold': True})
headings = ['Number', 'Value']
line_chart = workbook.add_chart({'type': 'line'})
line_chart.add_series({
'categories': '={1,2,3,4,5,6}',
'values': '={2,#N/A,2,3,4,#N/A}'
})
worksheet.insert_chart('F2', line_chart)
workbook.close()
I understand that if I changed it to the following, the problem would be fixed, however my aim is to use the above approach. If its not possible thats fine.
from xlsxwriter.workbook import Workbook
workbook = Workbook('chart.xlsx')
worksheet = workbook.add_worksheet()
bold = workbook.add_format({'bold': True})
headings = ['Number', 'Value']
data = [
[1, 2, 3, 4, 5, 6],
[2,'', 2, 3, 4,'=NA()'],
]
worksheet.write_row('A1', headings, bold)
worksheet.write_column('A2', data[0])
worksheet.write_column('B2', data[1])
line_chart = workbook.add_chart({'type': 'line'})
line_chart.add_series({
'categories': '=Sheet1!$A$2:$A$7',
'values': '=Sheet1!$B$2:$B$7',
})
worksheet.insert_chart('F2', line_chart)
workbook.close()
Unfortunately it is not possible unless the show #N/A as empty cell setting is selected (I dont believe it is a supported feature as it is relatively new for excel).
That is correct. It looks like that feature was added recently in Excel 16 (the XML element is <c16r3:dataDisplayOptions16>). So it isn't supported in XlsxWriter.
Note, it is possible to set the first 3 of those options using chart.show_blanks_as():
chart.show_blanks_as('span')
The available options are:
gap: Blank data is shown as a gap. The default.
zero: Blank data is displayed as zero.
span: Blank data is connected with a line.

how to update a portion of existing excel sheet with filtered dataframe?

I have an excel workbook with several sheets. I need to read a portion from one of the sheets, get a filtered dataframe and write a single value from that filtered dataframe to a specific cell in the same sheet. What is the best way to accomplish this, ideally without opening the excel workbook? I need to run this on linux, so can't use xlwings. I don't want to write the entire sheet, but just a selected cell/offset inside it. I tried the following to write to the existing sheet, but doesn't seem to work for me (no update occurs at the desired cell):
with pd.ExcelWriter('test.xlsx', engine='openpyxl') as writer:
writer.book = load_workbook('test.xlsx')
df_filtered.to_excel(writer, 'Sheet_Name', columns=['CS'], startrow=638, startcol=96)
Any tips would be helpful. Thanks.
If you're just writing a single cell the below should suffice.
import pandas as pd
import openpyxl
df = pd.DataFrame(data=[1,2,3], columns=['col'])
filtered_dataframe = df[df.col == 1].values[0][0]
filename = 'test.xlsx'
wb = openpyxl.load_workbook(filename)
wb['Sheet1'].cell(column=1, row=2, value=filtered_dataframe)
wb.save(filename)
I believe your issue was that you never called the save method of the writer.

How to delete Multiple rows in excel file using activex in Matlab

Activesheet.Rows.Item(1).Delete;
The above line will delete first row in the active excel sheet.
I want to delete multiple rows so I used the following line, but it did not work.
Activesheet.Rows.Item([1,2,5,64]).Delete;
If you want a full Matlab approach you could try this out:
rows_to_delete = [1 2 5 64];
data = xlsread(file_path);
data(rows_to_delete,:) = [];
delete(file_path);
xlswrite(file_path,data);
Using Excel COM:
Activesheet.Rows('1, 2, 5, 64').EntireRow.Delete
or:
Activesheet.Range('1, 2, 5, 64').Rows.EntireRow.Delete
You could even try a more consistent notation, eventually, using 1:1, 2:2, 5:5, 64:64 instead of 1, 2, 5, 64. But I always used the latter without problems in my code.

convert output formula to value?

I need to convert function fun(=SUMIF(B1:B16,B2,C1:C16)) into value so that I can use the output in another operation.
Moreover, I need to know which is the best module for working in excel and formatting cells.
import openpyxl
wb = openpyxl.load_workbook('file.xlsx')
ws = wb.active
# add a simple formula
ws['A3'] = ("=SUMIF(B1:B16,B2,C1:C16)")
wb.save("file.xlsx")
You could have a look at pyparsing, but I don't know, if it suits your needs best and can solve the given task.

Paste Special Transpose Syntax in Matlab using ActXServer

I am working on a code in Matlab that will open excel spreadsheet, copy a certain range, and paste it in a new sheet transposing my range in the process. I am completely stuck on the PasteSpecial method and cannot figure out how to make it transpose my data. I've tried everything I could think of: tried VBA-like syntax (Transpose=True), tried (Transpose, 1), tried ([],[],[],1), tried obj.Transpose(with all kinds of variations in the brackets)... and all kinds of other stuff to no avail. Please help me if anyone had done this before. Below if my simplified code in case it's needed. Thank you in advance!
Excel = actxGetRunningServer('excel.application');
set(Excel, 'Visible', 1);
Workbooks = Excel.Workbooks;
Workbook = Excel.Workbooks.Open('C:\Users\...test.xlsx');
curr_sheet = get(Workbook,'ActiveSheet');
rngObj = ('A1:C3')
rngObj.Copy
Sheets = Excel.ActiveWorkBook.Sheets;
new_sheet = Sheets.Add;
new_sheet.PasteSpecial; %This is where I am stuck!
The documentation for PasteSpecial has four input arguments to indicate the parameters of the paste operation. As you can see, the fourth option indicates whether to transpose the data or not.
new_sheet.PasteSpecial(NaN, NaN, NaN, true);

Resources