I need to export the custom grid to the csv file. I have used the below code in my listing.xml file.
<exportButton class="Magento\Ui\Component\ExportButton">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="options" xsi:type="array">
<item name="cvs" xsi:type="array">
<item name="value" xsi:type="string">csv</item>
<item name="label" xsi:type="string" translate="true">CSV</item>
<item name="url" xsi:type="string">catalogreport/export/gridToCsv</item>
</item>
<item name="xml" xsi:type="array">
<item name="value" xsi:type="string">xml</item>
<item name="label" xsi:type="string" translate="true">Excel XML</item>
<item name="url" xsi:type="string">catalogreport/export/gridToXml</item>
</item>
</item>
</item>
</argument>
</exportButton>
Then in my
Module/Controller/Adminhtml/Export/gridToCsv.php
class GridToCsv extends Action
{
public function execute()
{
$fileName = "CustomSales_". date('Ymd_His').".csv";
$dataSource = //The data fetches here;
$handle = fopen($fileName, 'w');
// Adding my logic to write the content to the file
$this->downloadCsv($fileName);
}
public function downloadCsv($fileName)
{
if (file_exists($fileName)) {
//set appropriate headers
header('Content-Description: File Transfer');
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename='.basename($fileName));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($fileName));
ob_clean();flush();
readfile($fileName);
}
}
}
This is working fine, The file is downloading successfully, But here my question is the CSV file is storing into the root directory, I need to change to pub/media/import
directory.
How this can be done here? I want to store the csv file inside pub/media/import
directory.
Can anyone suggest me please. Thanks!!