Package: json-excel-converter
JSON to excel converterA package that converts json to CSV, excel or other table formatsJSON to excel converterSample outputSimple jsonNested jsonjson with array propertyInstallationUsageSimple usageStreaming usage with restartsArraysXLSX FormattingCell formatColumn widthsRow heightsUrlsCustom cell renderingSample outputSimple json[{"col1":"val1","col2":"val2"}]the generated CSV/excel is:col1          col2
==================
val1          val2Nested json[{"col1":"val1","col2":{"col21":"val21","col22":"val22"}}]the generated CSV/excel is (in excel, col2 spans two cells horizontally):col1          col2
              col21         col22
=================================
val1          val21         val22json with array property[{"col1":"val1","col2":[{"col21":"val21"},{"col21":"val22"}]}]the generated CSV/excel is (in excel, col2 spans two cells horizontally):col1          col2         
              col21         col21
=================================
val1          val21         val22Installationpipinstalljson-excel-converter[extra]where extra is:xlsxwriterto use the xlsxwriterUsageSimple usagefromjson_excel_converterimportConverterfromjson_excel_converter.xlsximportWriterdata=[{'a':[1],'b':'hello'},{'a':[1,2,3],'b':'world'}]conv=Converter()conv.convert(data,Writer(file='/tmp/test.xlsx'))Streaming usage with restartsfromjson_excel_converterimportConverter,LinearizationErrorfromjson_excel_converter.csvimportWriterconv=Converter()writer=Writer(file='/tmp/test.csv')whileTrue:try:data=get_streaming_data()# custom function to get iterator of dataconv.convert_streaming(data,writer)breakexceptLinearizationError:passArraysWhen the first row is processed, the library guesses the columns layout. In case of arrays,
a column (or more columns if the array contains json objects) is created for each
of the items in the array, as shown in the example above.On subsequent rows the array might contain more items. The library reacts by adjusting
the number of columns in the layout and raisingLinearizationErroras previous rows might
be already output.Converter.convert_streamingjust raises this exception - it is the responsibility of caller
to take the right action.Converter.convertcaptures this error and restarts the processing. In case of CSV
this means truncating the output file to 0 bytes and processing the data again. XLSX writer
caches all the data before writing them to excel so the restart just means discarding the cache.If you know the size of the array in advance, you should pass it in options. Then no
processing restarts are required andLinearizationErroris not raised.fromjson_excel_converterimportConverter,Optionsfromjson_excel_converter.xlsximportWriterdata=[{'a':[1]},{'a':[1,2,3]}]options=Options()options['a'].cardinality=3conv=Converter(options=options)writer=Writer(file='/tmp/test.xlsx')conv.convert(data,writer)# orconv.convert_streaming(data,writer)# no exception occurs hereXLSX FormattingCell formatXLSX writer enables you to format the header and data by passing an array of header_formatters or
data_formatters. Take these fromjson_excel_converter.xlsx.formatspackage or create your own.fromjson_excel_converterimportConverterfromjson_excel_converter.xlsximportWriterfromjson_excel_converter.xlsx.formatsimportLastUnderlined,Bold,\Centered,Formatdata=[{'a':'Hello'},{'a':'World'}]w=Writer('/tmp/test3.xlsx',header_formats=(Centered,Bold,LastUnderlined,Format({'font_color':'red'})),data_formats=(Format({'font_color':'green'}),))conv=Converter()conv.convert(data,w)Seehttps://xlsxwriter.readthedocs.io/format.htmlfor details on formats in xlsxwriterColumn widthsPass the required column widths to writer:w=Writer('/tmp/test3.xlsx',column_widths={'a':20})Width of nested data can be specified as well:data=[{'a':{'b':1,'c':2}}]w=Writer('/tmp/test3.xlsx',column_widths={'a.b':20,'a.c':30,})To set the default column width, pass it asDEFAULT_COLUMN_WIDTHproperty:w=Writer('/tmp/test3.xlsx',column_widths={DEFAULT_COLUMN_WIDTH:20})Row heightsRow heights can be specified via therow_heightswriter option:w=Writer('/tmp/test3.xlsx',row_heights={DEFAULT_ROW_HEIGHT:20,# a bit taller rows1:40# extra tall header})UrlsTo render url, pass a function that gets data of a row and returns url to optionsdata=[{'a':'https://google.com'},]options=Options()options['a'].url=lambdadata:data['a']conv=Converter(options)conv.convert(data,w)Note:this will only be rendered in XLSX output, CSV output will silently
ignore the link.Custom cell renderingOverride thewrite_cellmethod. The method receivescell_data(instance ofjson_excel_converter.Value) anddata(the original
data being written to this row). Note that this method is used both
for writing header and rows - for header thedataparameter is None.classUrlWriter(Writer):defwrite_cell(self,row,col,cell_data,cell_format,data):ifcell_data.path=='a'anddata:self.sheet.write_url(row,col,'https://test.org/'+data['b'],string=cell_data.value)else:super().write_cell(row,col,cell_data,cell_format,data)