asp.net - tipo - exportar gridview a excel c# windows form
Exportar GridView a múltiples hojas de Excel (4)
En lugar de utilizar una biblioteca de terceros o la automatización de Excel (con su sobrecarga adicional), puede usar ADO.NET.
http://support.microsoft.com/kb/316934#10
Simplemente usaría el T-SQL que usaba con los objetos OleDbCommand.
CREATE TABLE Sheet1 (id INT, name char(255))
CREATE TABLE Sheet2 (id INT, name char(255))
// for inserts use a parameterized command with ?''s
INSERT INTO Sheet1 (id, name) VALUES(?, ?)
INSERT INTO Sheet1 (id, name) VALUES(?, ?)
Debería crear su archivo temp excel utilizando Path.GetTempFileName y sacarlo, después de lo cual puede eliminar el archivo temporal.
Tengo dos Gridview en mi aplicación web. Necesito, al hacer clic en el botón (ExcelExpot), los valores que se exportarán en Excel. De acuerdo con Sheet1 y Sheet2.
protected void ExportToExcel()
{
this.GridView1.EditIndex = -1;
Response.Clear();
Response.Buffer = true;
string connectionString = (string)ConfigurationSettings.AppSettings["ConnectionString"];
SqlConnection sqlconnection = new SqlConnection(connectionString);
String sqlSelect = "select * from login";
sqlconnection.Open();
SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter(sqlSelect, connectionString);
//DataTable dt1
DataTable dt1 =new DataTable();
mySqlDataAdapter.Fill(dt1);
//LinQ Query for dt2
var query = (from c in dt.AsEnumerable()
select new {id= c.Field<string>("id"),name=c.Field<string>("name"),city=c.Field<string>("city")}) ;
DataTable dt2 = new DataTable();
d2=query.CopyToDatatable();
DataSet ds=new DataSet();
ds.Tabls.Add(dt1);
ds.Tabls.Add(dt2);
Excel.Application excelHandle1 = PrepareForExport(ds);
excelHandle1.Visible = true;
}
// code for PrepareForExport(ds);
PrepareForExport(ds)
{
two tables in two worksheets of Excel...
}
Hacer esto con EPPlus es pan comido. No se requieren ensambles Interop y literalmente 2 líneas de código hacen toda la magia:
ws.Cells["A1"].LoadFromDataTable(dt1, true);
ws2.Cells["A1"].LoadFromDataTable(dt2, true);
Código completo:
protected void ExportExcel_Click(object sender, EventArgs e)
{
//LinQ Query for dt2
var query = (from c in dt.AsEnumerable()
select new {id= c.Field<string>("id"),name=c.Field<string>("name"),city=c.Field<string>("city")}) ;
DataTable dt2 = new DataTable();
dt2=query.CopyToDatatable();
//DataTable dt1
DataTable dt1 =new DataTable();
mySqlDataAdapter.Fill(dt1);
using (ExcelPackage pck = new ExcelPackage())
{
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Page 1");
ExcelWorksheet ws2 = pck.Workbook.Worksheets.Add("Page 2");
ws.Cells["A1"].LoadFromDataTable(dt1, true);
ws2.Cells["A1"].LoadFromDataTable(dt2, true);
//Write it back to the client
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment; filename=ExcelDemo.xlsx");
Response.BinaryWrite(pck.GetAsByteArray());
Response.Flush();
Response.End();
}
}
Tenga en cuenta que copié y pegué su código para recopilar los datos. Espero que estas líneas produzcan una DataTable.
Tendrá que crear el libro de trabajo, agregar más hojas si es necesario (de forma predeterminada con tres) y luego completar las celdas.
Parte superior del archivo:
using Excel=Microsoft.Office.Interop.Excel;
Y luego el código principal para generar el archivo de Excel
Excel.Application excel = new Application();
var workbook = (Excel._Workbook) (excel.Workbooks.Add(Missing.Value));
for (var i = 0; i < dataset.Tables.Count; i++)
{
if (workbook.Sheets.Count <= i)
{
workbook.Sheets.Add(Type.Missing, Type.Missing, Type.Missing,
Type.Missing);
}
var currentSheet = (Excel._Worksheet)workbook.Sheets[i];
for (var y = 0; y < dataset.Tables[i].Rows.Count; y++)
{
for (var x = 0; x < dataset.Tables[i].Rows[y].ItemArray.Count(); x++)
{
currentSheet.Cells[y, x] = dataset.Tables[i].Rows[y].ItemArray[x];
}
}
}
workbook.SaveAs("C://Temp//book.xlsx", Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, XlSaveAsAccessMode.xlNoChange,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing);
workbook.Close();
excel.Quit();
Response.WriteFile(C://Temp//book.xlsx");
No sé exactamente si esto funcionará, pero debería llevarlo en la dirección correcta
(también: Type.Missing
y Missing.Value
provienen del espacio de nombres System.Reflection
, solo FYI)
Estoy de acuerdo con @Andrew Burgess y he implementado su código en uno de mis proyectos. Solo para el registro hay algunos pequeños errores en el código que causarán algunas excepciones COM. El código corregido está debajo (el problema era que Excel numera las hojas, las filas, las columnas de 1 a n no desde cero).
using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection;
using System.IO;
//Print using Ofice InterOp
Excel.Application excel = new Excel.Application();
var workbook = (Excel._Workbook)(excel.Workbooks.Add(Missing.Value));
for (var i = 0; i < dataset.Tables.Count; i++)
{
if (workbook.Sheets.Count <= i)
{
workbook.Sheets.Add(Type.Missing, Type.Missing, Type.Missing,
Type.Missing);
}
//NOTE: Excel numbering goes from 1 to n
var currentSheet = (Excel._Worksheet)workbook.Sheets[i + 1];
for (var y = 0; y < dataset.Tables[i].Rows.Count; y++)
{
for (var x = 0; x < dataset.Tables[i].Rows[y].ItemArray.Count(); x++)
{
currentSheet.Cells[y+1, x+1] = dataset.Tables[i].Rows[y].ItemArray[x];
}
}
}
string outfile = @"C:/APP_OUTPUT/EXCEL_TEST.xlsx";
workbook.SaveAs( outfile, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing);
workbook.Close();
excel.Quit();