0
I created a program to export a Dataset to excel at runtime via Response, but when opening the file a message of incompatibility between the file format and the file extension is displayed.
Follows code:
DataTable dt = new DataTable();
DataSet ds = new DataSet();
int IdEmpresa = this.Master.UsuarioLogado.IdEmpresa;
UpQuesitoRespostaBLL uqr = new UpQuesitoRespostaBLL();
List<UpQuesitoCargoResposta> lstOpcoesRespostas = uqr.ListarOpcoesRespostasPorEmpresa(IdEmpresa);
int qtdeRespostas = lstOpcoesRespostas.FirstOrDefault().Respostas.Count();
dt.Columns.Add("Quesito");
dt.Columns.Add("Area");
dt.Columns.Add("Cargo");
dt.Columns.Add("Peso");
for (int i = 1; i <= qtdeRespostas; i++)
{
dt.Columns.Add("Valor_" + i);
dt.Columns.Add("Resposta_" + i);
}
foreach (var resp in lstOpcoesRespostas)
{
DataRow row = dt.NewRow();
row[0] = resp.DsQuesito.ToString();
row[1] = resp.DsArea.ToString();
row[2] = resp.DsCargo.ToString();
row[3] = resp.Peso.ToString();
int j = 3;
for (int i = 0; i < qtdeRespostas; i++)
{
row[j + 1] = resp.Respostas[i].Valor.ToString();
row[j + 2] = resp.Respostas[i].DsResposta.ToString();
j += 2;
}
dt.Rows.Add(row);
}
ds.Tables.Add(dt);
StringWriter sw = DataSetToExcel(ds);
string date = DateTime.Now.ToShortDateString().Replace("/", "-").ToString();
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=RespostasPerformance" + date + ".xls");
HttpContext.Current.Response.Charset = "";
HttpContext.Current.Response.End();
I’ve already modified the contenttype and header extension, but no attempt worked.
The error is in the format or the way I am exporting ?
He opens the file after or after?
– Leandro Angelo
the file opens, a message appears saying that there is a difference between the format and the extension, ask me if I want to open it anyway. By clicking Yes the file opens normally
– Guilherme Tavares
There’s a package that does that for you, use them easier
– novic
@Guilhermetavares This is because you are not actually building an excel file, just saving a file with a structure that it can do the conversion with the extension
.xls
.– Leandro Angelo
Some indication Virgilio ?
– Guilherme Tavares
@Leandroangelo then you advise build another way, without the dataset ??
– Guilherme Tavares