我使用以下代码将带有图像的数据导出到Excel
。
代码
protected void ExportToExcel(object sender, EventArgs e) { //Get the data from database into datatable string strQuery = "select CustomerID, ContactName, City, PostalCode, display_picture" + " from customers"; SqlCommand cmd = new SqlCommand(strQuery); DataTable dt = GetData(cmd); //Create a dummy GridView GridView GridView1 = new GridView(); GridView1.AllowPaging = false; GridView1.DataSource = dt; GridView1.DataBind(); Response.Clear(); Response.Buffer = true; Response.AddHeader("content-disposition", "attachment;filename=DataTable.xls"); Response.Charset = ""; Response.ContentType = "application/vnd.ms-excel"; StringWriter sw = new StringWriter(); HtmlTextWriter hw = new HtmlTextWriter(sw); for (int i = 0; i .textmode { mso-number-format:\@; } "; Response.Write(style); Response.Output.Write(sw.ToString()); Response.Flush(); Response.End(); }
Excel
正在正常下载。但问题是当我过滤Excel
中的数据时。 Excel
中的图片属于Move but don't size with cells
属性。如何使用属性Move and size with cells
生成图像?
答案 0 :(得分:2)
您的代码根本不会创建Excel文件,它会创建一个HTML表格,并使用旧的二进制Excel格式(xls)的伪内容类型发送它。 Excel不会被欺骗,它会检测到这是一个HTML表并尝试使用默认设置导入它。这可能由于多种原因而中断。
使用像EPPlus这样的库创建真实的Excel文件要容易得多,也便宜得多。对于初学者,您可以直接从DataTable填充工作表:
protected void ExportToExcel(object sender, EventArgs e)
{
///...
DataTable dt = GetData(cmd);
using (ExcelPackage pck = new ExcelPackage())
{
//Create the worksheet
var ws = pck.Workbook.Worksheets.Add("Demo");
//Load the datatable into the sheet, starting from cell A1.
//Print the column names on row 1
ws.Cells["A1"].LoadFromDataTable(dt, true);
//That's it!
//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());
}
}
您可以使用Drawings.AddPicture
方法添加图片:
ExcelPicture pic = ws.Drawings.AddPicture("pic1", new FileInfo("PathToMyImage.png"));
结果是一个xlsx
文件,它是一个压缩的XML文件包。这意味着它实际上小于比通常生成的HTML表格或CSV文件而不是实际的Excel文件。
答案 1 :(得分:1)
EasyXLS是一个库,它还可以使用图像导出xlsx和xls文件。
//Create a workbook
ExcelDocument workbook = new ExcelDocument();
//Add a worksheet
ExcelWorksheet worksheet = new ExcelWorksheet("Gridview");
workbook.easy_addWorksheet(worksheet);
//Add the gridview to the worksheet
DataSet dataSet = new DataSet();
dataSet.Tables.Add((DataTable)GridView1.DataSource);
worksheet.easy_insertDataSet(dataSet);
//Add an image
worksheet.easy_addImage("image.jpg", "A10");
//Exporting gridview with image
workbook.easy_WriteXLSXFile("DataTable.xlsx");
有关插入图片的更多信息,请访问:
http://www.easyxls.com/manual/basics/excel-image-import-export.html
如果从数据库加载图像字节,则需要在机器上本地临时保存图像。
您还可以查看how to export gridview to excel以查看有关格式化数据的详情。