C#. net core 6, winforms application, TekerikNuGet3 package source, UI.for.WinForms.AllControls.NetCore package 2022.2.622
I am trying to export selected cells from a RadGridView as a csv file.
When using "var exporter = new ExportToCSV(Dgv)" then "exporter.RunExport(fileName);" writes the csv file correctly. It exports every cell.
It doesn't support exporting selections so I wrote a function to do this . The one below is what I used in my project to test what I was doing. It initially writes the csv to a worksheet and wrote that using formatprovider to file, then I just created a stringbuilder adding quotes and appended that to the file afterwards.
Writing the worksheet, the csv values haven't been quoted, plus number fields have had leading zeros removed which proves to be a problem when telephone numbers are stored in a field.
So I googled and found the Settings property which is there to set csv options. But they are private, not public therefore I can't set up the csv propertly.
private void radButton1_Click(object sender, EventArgs e)
{
var workbook = new Workbook();
var worksheet = workbook.Worksheets.Add();
var rowIndex = 0;
var columnIndex = -1;
var sb = new StringBuilder();
var prevColumnIndex = -1;
// ForEach cell are accessed vertically then horizontally.
foreach (var cell in Dgv.SelectedCells)
{
// Cell is included in selection even if it's invisible
// so check visibility and ignore if it isnt
if (!cell.ColumnInfo.IsVisible) continue;
// At bottom of column, rownum will change. Watch for this
// and reset x and y values
var rowNum = cell.RowInfo.Index;
if (rowNum != prevColumnIndex)
{
prevColumnIndex = rowNum;
rowIndex = 0;
columnIndex++;
sb.AppendLine("");
}
else if (!string.IsNullOrEmpty(sb.ToString()))
sb.Append(",");
var value = cell.Value;
worksheet.Cells[columnIndex, rowIndex++ ].SetValue(value.ToString());
sb.Append($"\"{value.ToString()}\"");
}
var fileName = @"C:\temp\SampleFile.csv";
IWorkbookFormatProvider formatProvider = new CsvFormatProvider();
using var output = new FileStream(fileName, FileMode.Create);
formatProvider.Export(workbook, output);
output.Close();
// Write contents of sb to the file for comparison sake
File.AppendAllText(fileName, sb.ToString());
}