Code for Importing data through Excel in D365 F&O:
using OfficeOpenXml;
using OfficeOpenXml.ExcelPackage;
using OfficeOpenXml.ExcelRange;
using System.IO;
class ImportCustomerData
{
public void run()
{
ttsbegin;
this.updateDailyAttendance();
ttscommit;
}
void updateDailyAttendance()
{
System.IO.Stream stream;
ExcelSpreadsheetName sheeet;
FileUploadBuild fileUpload;
DialogGroup dlgUploadGroup;
FileUploadBuild fileUploadBuild;
FormBuildControl formBuildControl;
CustTable CustTable, insertCustTable;
COMVariantType type;
Dialog dialog = new Dialog("Customers Import");
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;
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);
for (i = 2; i<= rowCount; i++)
{
CustAccount custId;
TransDate WorkingDate;
custId = (range.get_Item(i, 1).value);
//WorkingDate = str2Date((range.get_Item(i, 2).value),123);
select forupdate CustTable
where CustTable.AccountNum == custId;
//&& CustTable.WorkingDate == WorkingDate;
if(CustTable) //if record already exists update it
{
CustTable.selectForUpdate(true);
CustTable.Currency = any2Str(range.get_Item(i, 3).value);
CustTable.CustGroup = any2Str(range.get_Item(i, 4).value);
//CustTable.InvoiceAccount = any2Real(range.get_Item(i, 5).value);
ttsbegin;
CustTable.update();
ttscommit;
}
Else //insert the new record
{
insertCustTable.AccountNum = (range.get_Item(i, 1).value);
//insertCustTable.WorkingDate = str2Date((range.get_Item(i, 2).value),123);
insertCustTable.Currency = any2Str(range.get_Item(i, 3).value);
insertCustTable.CustGroup = any2Str(range.get_Item(i, 4).value);
//insertCustTable.OT = any2Real(range.get_Item(i, 5).value);
insertCustTable.insert();
}
}
}
}
else
{
error("Exception error");
}
}
}
public static void main (Args args)
{
ImportCustomerData ImportCustomerData;
ImportCustomerData = new ImportCustomerData ();
ImportCustomerData.run();
}
}