Skip to content

Instantly share code, notes, and snippets.

@ddieppa
Last active July 2, 2021 14:17
Show Gist options
  • Save ddieppa/315fea737e88e82c875d5f95d3470745 to your computer and use it in GitHub Desktop.
Save ddieppa/315fea737e88e82c875d5f95d3470745 to your computer and use it in GitHub Desktop.
using ClosedXML.Excel;
using Dapper;
private void ExportByBankWithoutMapping(long batchId,
TemplateType templateType,
string sprocName,
string templatePath,
string fileNameTemplate,
string worksheetName = "Data")
{
var values = ExecuteQueryDapper(ConnectionString,
sprocName,
new { batchId });
var fileName = GetFileNameWithTicks(fileNameTemplate);
var excelContent = GenerateExcel(values, templatePath, worksheetName);
_blobService.UploadContentBlobAsync(excelContent,
fileName,
templateType);
}
private string GetFileNameWithTicks(string originalFileName) =>
string.Format(CultureInfo.InvariantCulture,
originalFileName,
DateTime.Now.Ticks);
public string GenerateExcel(List<object[]> values,
string templatePath,
string worksheetName,
int startRowPosition = 2,
int startColumnPosition = 1)
{
try
{
using var memoryStream = new MemoryStream();
using var workbook = new XLWorkbook(templatePath);
var ws = workbook.Worksheet(worksheetName);
var range = ws.Cell(startRowPosition, startColumnPosition).InsertData(values);
workbook.SaveAs(memoryStream, new SaveOptions()
{
ValidatePackage = true,
EvaluateFormulasBeforeSaving = true,
ConsolidateDataValidationRanges = true,
GenerateCalculationChain = true
});
var excelContentString = Convert.ToBase64String(memoryStream.ToArray());
return excelContentString;
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
public List<object[]> ExecuteQueryDapper(string connectionString,
string query,
object parameters,
CommandType commandType = CommandType.StoredProcedure)
{
using var connection = new SqlConnection(connectionString);
var sprocResults = connection.Query(query, parameters, commandType: commandType).ToList(); //return IEnumerable of DapperRow
var dictionaryOfResults = sprocResults.Select(x => (IDictionary<string, object>)x); //convert DapperRow into Dictionary<string, object>
var resultList = dictionaryOfResults.Select(d => d.Values.ToArray()).ToList(); //Convert Dictionary into List<Object[]>
return resultList;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment