D365 FO - Import data from excel file
Create Table ImportProductTable with 2 Fields
Create xlsx excel file with 2 fields ItemID , ItemName
using System.IO;
using OfficeOpenXml;
using OfficeOpenXml.ExcelPackage;
using OfficeOpenXml.ExcelRange;
public static class EcoResProductListPage_Extension
{
[FormControlEventHandler(formControlStr(EcoResProductListPage, UploadProductButtonControl), FormControlEventType::Clicked)]
public static void UploadProductButtonControl_OnClicked(FormControl sender, FormControlEventArgs e)
{
System.IO.Stream stream;
ExcelSpreadsheetName sheeet;
FileUploadBuild fileUpload;
DialogGroup dlgUploadGroup;
FileUploadBuild fileUploadBuild;
FormBuildControl formBuildControl;
ImportProductTable _ImportProductTable;
COMVariantType type;
Dialog dialog = new Dialog('Import Products');
int rowCount2=10;
dlgUploadGroup = dialog.addGroup('@SYS54759');
formBuildControl = dialog.formBuildDesign().control(dlgUploadGroup.name());
fileUploadBuild = formBuildControl.addControlEx(classstr(FileUpload), 'Upload');
fileUploadBuild.style(FileUploadStyle::MinimalWithFilename);
fileUploadBuild.fileTypesAccepted('.xlsx');
str COMVariant2Str(COMVariant _cv)
{
switch (_cv.variantType())
{
case COMVariantType::VT_BSTR:
return _cv.bStr();
case COMVariantType::VT_EMPTY:
return'';
default:
throw error(strfmt('@SYS26908', _cv.variantType()));
}
}
if (dialog.run() && dialog.closedOk())
{
FileUpload fileUploadControl = dialog.formRun().control(dialog.formRun().controlId('Upload'));
FileUploadTemporaryStorageResult fileUploadResult = fileUploadControl.getFileUploadResult();
if (fileUploadResult != null && fileUploadResult.getUploadStatus())
{
stream = fileUploadResult.openResult();
using (ExcelPackage Package = new ExcelPackage(stream))
{
int rowCount, i,columncount,j;
RecId _RecId;
Package.Load(stream);
ExcelWorksheet worksheet = package.get_Workbook().get_Worksheets().get_Item(1);
OfficeOpenXml.ExcelRange range = worksheet.Cells;
rowCount = (worksheet.Dimension.End.Row) - (worksheet.Dimension.Start.Row) + 1;
columncount = (worksheet.Dimension.End.Column);
ttsbegin;
delete_from _ImportProductTable;
ttscommit;
for (i = 2; i<= rowCount; i++)
{
_ImportProductTable.ItemId = range.get_Item(i, 1).value ;
_ImportProductTable.ItemName = range.get_Item(i, 2).value ;
_ImportProductTable.insert();
}
info(strFmt("%1 rows inserted.",rowCount));
}
}
else
{
error('Error here');
}
}
}
}
No comments:
Post a Comment