Requirement
Import records from CSV file into D365/AX table using X++ code.
Sample Code
[code language=”cpp”]
class ACXInventBatchImport
{
public static void main(Args _args)
{
AsciiStreamIo file;
Array fileLines;
FileUploadTemporaryStorageResult fileUpload;
ItemId itemId;
InventBatchId inventBatchId;
MaximumRetailPrice_IN mrp, mrpMultiple;
AcxMfgInventBatchId mfgInventBatchID;
ExpirationDate expDate;
real qtyMultiple;
InventTable inventTable;
//Upload a file
fileUpload = File::GetFileFromUser() as FileUploadTemporaryStorageResult;
file = AsciiStreamIo::constructForRead(fileUpload.openResult());
if (file)
{
if (file.status())
{
throw error(“@SYS52680”);
}
file.inFieldDelimiter(‘,’); // CSV must have Comma , separator
file.inRecordDelimiter(‘\r\n’);
}
//Read a CSV File
container rec;
while (!file.status())
{
rec = file.read();
if (conLen(rec))
{
itemId = conPeek(rec,1);
inventBatchId = conPeek(rec,2);
mrp = str2Num(conPeek(rec,3));
mrpMultiple = str2Num(conPeek(rec,4));
mfgInventBatchID = conPeek(rec,5);
qtyMultiple = str2Num(conPeek(rec,6));
expDate = str2Date(conPeek(rec,7), 123);
select firstonly1 inventTable
where inventTable.ItemId == itemId;
if (inventTable.RecId)
{
InventBatch inventBatch = InventBatch::find(inventBatchId, itemId, true);
if (inventBatch.RecId == 0)
{
inventBatch.clear();
inventBatch.itemId = itemId;
inventBatch.inventBatchId = InventBatchId;
inventBatch.AcxMfgInventBatchId = mfgInventBatchID;
inventBatch.prodDate = today();
inventBatch.AcxMaximumRetailPrice_IN = mrp;
inventBatch.AcxMaximumRetailPrice_INMultiples = mrpMultiple;
inventBatch.AcxQtyMultiples = qtyMultiple;
inventBatch.expDate = expDate;
inventBatch.insert();
}
else
{
ttsbegin;
inventBatch.AcxMfgInventBatchId = mfgInventBatchID;
inventBatch.AcxMaximumRetailPrice_IN = mrp;
inventBatch.AcxMaximumRetailPrice_INMultiples = mrpMultiple;
inventBatch.AcxQtyMultiples = qtyMultiple;
inventBatch.expDate = expDate;
inventBatch.doUpdate();
ttscommit;
}
}
else
{
error(strfmt(‘Item Doesnot Exists.Item Code = %1’, itemId));
}
}
}
info(“done”);
}
}
[/code]
Cheers 🙂
Piyush Adhikari
Hello,
I used your code to import an excel file. but it shows the error that file wasn’t uploaded. also when I debug the code, It’s not coming in my class
This program will only work for csv