Как запретить FastReport экспортировать все данные в один столбец Excel?C#

Место общения программистов C#
Ответить
Anonymous
 Как запретить FastReport экспортировать все данные в один столбец Excel?

Сообщение Anonymous »

Я пытаюсь экспортировать отчет в Excel с помощью FastReport в своем приложении ASP.NET Core. Однако когда я создаю файл Excel, все данные отображаются в одном столбце, а не разделяются должным образом на несколько столбцов.
Ниже приведен мой текущий код:

Код: Выделить всё

 public class DosyaOlusturService : IDosyaOlusturService {

public byte[] DosyaOlustur(string html, ReportsParametersVm reportsParametersVm, string path)
{
string filePath = path + reportsParametersVm.OutputFileName;  // Dosya yolu

if (reportsParametersVm.ButtonName == "PDF")
{
try
{
var htmlToPdf = new HtmlToPdfConverter
{

CustomWkHtmlArgs = "--dpi 300 --enable-local-file-access --disable-smart-shrinking --zoom 0.6",
PageWidth = 210,
PageHeight = 297,
Margins = new PageMargins { Top = 5, Bottom = 5, Left = 2, Right = 2 },
Orientation = reportsParametersVm.PdfLandscape == true ? PageOrientation.Landscape : PageOrientation.Portrait,

};
var pdfBytes = htmlToPdf.GeneratePdf(html);

File.WriteAllBytes(filePath, pdfBytes);

return pdfBytes;
}
catch (Exception)
{
return new byte[0];
}
}
else
{
try
{
// Dosyayı oluştur ve yazma modunda aç
using (StreamWriter writer = new StreamWriter(filePath))
{
writer.WriteLine(html);
}

// Oluşturulan dosyayı oku
byte[] fileBytes = File.ReadAllBytes(filePath);
return fileBytes;
//return File(fileBytes, "application/octet-stream", fileName);

}
catch (Exception ex)
{
return new byte[0];
//Console.WriteLine($"Hata oluştu: {ex.Message}");
}
}

}

public RaporOlusturResponse FastReportRaporOlusturPDF(DataTable dataTable, ReportsParametersVm reportsParametersVm, bool isSendFromMail)
{

Report report = new Report();

FastReport.Utils.Config.WebMode = true;

string reportPath = Path.Combine(Directory.GetCurrentDirectory(), $"Views\\Reports\\FastReports\\Rpr_{reportsParametersVm.Code}.frx");

report.Load(reportPath);

string viewName = $"vw_{reportsParametersVm.Code}";
report.RegisterData(dataTable, viewName);

using MemoryStream ms = new();
PDFSimpleExport pdfExport = new PDFSimpleExport();

string outputPath = isSendFromMail ? Path.Combine(Directory.GetCurrentDirectory(), $"Content\\MailAttachments\\{reportsParametersVm.OutputFileName}") :
Path.Combine(Directory.GetCurrentDirectory(), $"Content\\CreatedReports\\{reportsParametersVm.OutputFileName}");

try
{
report.Prepare();
}
catch (Exception ex)
{
Console.WriteLine($"Prepare Hatası: {ex.Message}");
}

try
{
report.Prepare();
report.Export(pdfExport, ms);
}
catch (Exception ex)
{
Console.WriteLine($"Export Hatası: {ex.Message}");
}

ms.Position = 0;

var fileBytes = ms.ToArray();

// PDF dosyasını diske kaydet

System.IO.File.WriteAllBytes(outputPath, fileBytes);

return new RaporOlusturResponse()
{
File = new FileModel()
{
FileBytes = isSendFromMail ? fileBytes :  null,
MimeType = reportsParametersVm.ReportMimeType,
OutputFileName = reportsParametersVm.OutputFileName,
OutputFilePath = outputPath,
},
Message = "Başarılı",
IsSucces = true
};
}

public RaporOlusturResponse FastReportRaporOlusturEXCEL(DataTable dataTable, ReportsParametersVm reportsParametersVm, bool isSendFromMail)
{
Report report = new Report();
FastReport.Utils.Config.WebMode = true;

string reportPath = Path.Combine(Directory.GetCurrentDirectory(), $"Views\\Reports\\FastReports\\Rpr_{reportsParametersVm.Code}.frx");
report.Load(reportPath);

string viewName = $"vw_{reportsParametersVm.Code}";

// Create a DataSet and add the DataTable to it
DataSet dataSet = new DataSet();
dataTable.TableName = viewName;
dataSet.Tables.Add(dataTable);

// Register the DataSet
report.RegisterData(dataSet, viewName, true);

// Update the dictionary to reflect the data source
report.Dictionary.DataSources.Clear();
report.Dictionary.RegisterData(dataSet, viewName, true);

using MemoryStream ms = new();
HTMLExport htmlExport = new HTMLExport();

string outputPath = isSendFromMail ? Path.Combine(Directory.GetCurrentDirectory(), $"Content\\MailAttachments\\{reportsParametersVm.OutputFileName}") :
Path.Combine(Directory.GetCurrentDirectory(), $"Content\\CreatedReports\\{reportsParametersVm.OutputFileName}");

try
{
report.Prepare();
}
catch (Exception ex)
{
Console.WriteLine($"Prepare Error: {ex.Message}");
}

try
{
report.Export(htmlExport, ms);
DosyaOlustur(htmlExport.ToString(), reportsParametersVm, outputPath);
}
catch (Exception ex)
{
Console.WriteLine($"Export Error: {ex.Message}");
}

ms.Position = 0;
var fileBytes = ms.ToArray();

File.WriteAllBytes(outputPath, fileBytes);

return new RaporOlusturResponse()
{
File = new FileModel()
{
FileBytes = isSendFromMail ? fileBytes : null,
MimeType = reportsParametersVm.ReportMimeType,
OutputFileName = reportsParametersVm.OutputFileName,
OutputFilePath = outputPath,
},
Message = "Success",
IsSucces = true
};
}}
Я хочу, чтобы в созданном файле Excel данные правильно отображались в отдельных столбцах. Но это выглядит так, как показано ниже;
Изображение
< /p>
В таблице DataTable есть несколько столбцов, но файл Excel помещает все данные в один столбец.
Чего мне не хватает в процессе настройки или экспорта? Как это исправить, чтобы экспортированный файл Excel был правильно структурирован?
Будем очень признательны за любую помощь или рекомендации!

Подробнее здесь: https://stackoverflow.com/questions/793 ... n-in-excel
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»