Package: django-excel-tools
Django Excel ToolsSerializing excel data to python format for easier to manage.RequirementsDjango (1.8 or higher version)OpenPYXLInstallationInstall via pippipinstalldjango-excel-toolsDocumentationSerializer Overridable FunctionsFields ReferencesCommon ArgumentBooleanFieldCharFieldIntegerFieldDateFieldDateTimeFieldExample UsageSerializer Overridable Functionsrow_extra_validationThis function will call each time a row has been validated.
This is for the case where you want a row of excel data that has been
validated and then you want to add your own validation.extra_clean_{field name}This function will be call when a column cell is validated and you would like to add custom validation.field namemust be match with field name defined inMeta.fields.validatedThis function will be call when all data in excel is validated.invalidThis function will be call when there are one or more errors happen during data validation. Simply putvalidation_errorsis not empty.operation_failedThis function will be call when there are one or more errors happen during import operation. Simply putoperation_errorsis not empty.operation_successThis function will be call when there is no error happen during import operation. Simply putoperation_errorsis empty.import_operationThis function will be call after all data in excel is validated, and this is also the place where you add your function of how you gonna insert all the cleaned excel data to your database. Check usage below for the example code.Fields ReferencesCommon Argumentverbose_nameThis field will be used in case of error, so we know exactly which column fix.BooleanFieldRequired argument:verbose_nameCorresponds todjango_excel_tools.fields.BooleanFieldCharFieldRequired arguments:max_lengthThe max length of text that is acceptable.verbose_nameThis field will be used in case of error, so we know exactly which column fix.Optional arguments:convert_numberautomatically convert int or number to string. DefaultTrue.choicesonly accept value in choices if not matchValidationErrorwill raise. DefaultNone.defaultthis value will be used when excel is blank. DefaultNone.case_sensitivethis is used in case of choices are set, comparing choices with case sensitive or not. DefaultTrue.Corresponds todjango_excel_tools.fields.CharFieldIntegerFieldRequired arguments:verbose_nameOptional arguments:defaultthis value will be used when excel is blank. Default isNoneconvert_strthis value will be used to convert string to int, if failedValidationErrorwill be raised. Default isTrue.blankthis tell the field is allowed to blank or not. Default isFalse.choicesthis tell the field is only accept value from choices, otherwiseValidationErrorwill be raised. Default isNone.Corresponds todjango_excel_tools.fields.IntegerFieldDateFieldRequired arguments:date_formatThis will be use for string formatting date from string.date_format_verboseThis will be used when error occurred, so that user may know how to change to the correct format.verbose_nameOptional Arguments:blankthis tell the field is allowed to blank or not. Default isFalse.Corresponds todjango_excel_tools.fields.DateFieldDateTimeFieldRequired arguments:date_formatThis will be use for string formatting date from string.date_format_verboseThis will be used when error occurred, so that user may know how to change to the correct format.verbose_nameOptional Arguments:blankthis tell the field is allowed to blank or not. Default isFalse.Corresponds todjango_excel_tools.fields.DateTimeFieldExample UsageClass Excel Serializerfromdjango_excel_toolsimportserializersclassStaffExcelSerializer(serializers.ExcelSerializer)GENDER_CHOICES=['male','female']code=serializers.IntegerField(verbose_name='Code')name=serializers.CharField(max_length=100,verbose_name='Name')gender=serializers.CharField(max_length=5,verbose_name='GENDER',choices=GENDER_CHOICES)date_of_birth=serializers.DateField(blank=True,date_format='%Y-%m-%d',date_format_verbose='YYYY-MM-DD',verbose_name='Date of Birth')classMeta:start_index=1fields=('code','name','gender','date_of_birth')enable_transaction=True# Default is Truedefrow_extra_validation(self,index,cleaned_row):# Code 100 must be femalecode=cleaned_row['code']gender=clenaed_row['gender']ifcode!=100:returncleaned_rowifgender!='female':raiseserializers.exceptions.ValidationError(message='[Row{index}]{message}'.format(index=index,message='Code 100 cannot be other than female')returncleaned_rowdefextra_clean_name(self,cleaned_value):return'Hello{}'.format(cleaned_value)defvalidated(self):# Notified that excel is successfully validateddefinvalid(self,errors):# Notify that excel format is not valid and errors argument is# the list of errors messagedefoperation_failed(self,errors):# Error during import operationdefoperation_success(self):# Import operation successdefimport_operation(self,cleaned_data):forindex,rowinenumerate(cleaned_data):try:Staff.objects.create(**row)exceptExceptionase:self.operation_errors.append(self.gen_error(index,str(e)))continueUsagefromopenpyxlimportload_workbookdefimport_view(request):excel_file=request.files[0]workbook=load_workbook(file)worksheet=workbook.worksheets[0]serializer=StaffExcelSerializer(worksheet=worksheet)ifserializer.validation_errors:returnResponse(data=serializer.validation_errors,status=400)ifserializer.operation_errors:returnResponse(data=serializer.operation_errors,status=400)returnResponse(status=201)LicenseMIT LicenseCopyright (c) 2017, Khemanorak KhathPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.ChangelogAll notable changes to this project will be documented in this file.The format is based onKeep a Changelog,
and this project adheres toSemantic Versioning.[1.0.1] - 2018-12-11ChangedRemovedBASE_MESSAGEin fieldsAddedTranslation for Japanese and Khmererror_transutil function for generate error messageFixedAdded validation for columns in excel is less than defined in serializer fields[1.0.0] - 2018-10-19Breaking ChangeMeta.django_enable_transaction has changed to enable_transactionChangedMoved all fields class fromdjango_excel_tools.serializerstodjango_excel_tools.fieldsCode refactored fordjango_excel_tools.serializers.ExcelSerializerto more readable and pure function that doesn't produce effect.AddedMore test coverage