我正在从网页导出数据到Excel.这应该是没有道理的,但<p>数据中有标签.这会导致Excel在数据全部位于同一单元格中时创建新行.经过一些研究后,我发现mso-data-placement应该可以解决问题,但它不起作用.Excel打开,显示数据,但会创建额外的不确定行.这是我用来导出数据的代码:
protected void doexcel()
{
string style = @"<style type='text/css'>P {mso-data-placement:same-cell; font-weight:bold;}</style>";
HttpResponse response = HttpContext.Current.Response;
// first let's clean up the response.object
response.Clear();
response.Charset = "";
//set the response mime type for excel
response.ContentType = "application/vnd.ms-excel";
Random RandomClass = new Random();
int RandomNumber = RandomClass.Next();
String filename = "a" + RandomNumber + DateTime.Now + ".xls";
response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"" );
// create a string writer
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
HttpContext.Current.Response.Write(style);
SqlDataSourceEmployeeAssets.ConnectionString = MyObjects.Application.CurrentContext.ConnectionString;
String sql = (string)Session["sql"];
SqlDataSourceEmployeeAssets.SelectCommand = sql;
// lCount.Text = "Query returned " + getCount(query) + " rows.";
DataGrid dge = new DataGrid();
dge.DataSource = SqlDataSourceEmployeeAssets;
dge.DataBind();
dge.RenderControl(htw);
response.Write(sw.ToString());
response.End();
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是数据库中原始数据给我带来悲伤的一个例子:
<P>4/13/2011 : Cheng "Jonathan" Vaing is with BSES Graffiti Unit.</P><P>4/13/2011 : Cheng "Jonathan" Vaing is with</P>
Run Code Online (Sandbox Code Playgroud)
建议?
我尝试了其他几件事
<P style="mso-data-placement:same-cell> my data </p>
<style type='text/css'>P {mso-highlight:yellow}</style>";
为什么哦为什么Excel不能识别我的mso-*属性?!?!
有一个解决方案,但它不干净。
在 dge.DataBind 之后,放置以下代码。这将对每个单元格的文本进行编码
foreach (DataGridItem dgi in dge.Items)
{
foreach (TableCell cell in dgi.Cells)
{
cell.Text = WebUtility.HtmlEncode(cell.Text);;
}
}
Run Code Online (Sandbox Code Playgroud)
Excel 文件打开后,应在一个单元格中显示带有标记的原始数据。
我发现这很有效,因为 Excel 实际上也对文本进行了编码。要查看 Excel 的实际操作,请执行以下操作:
希望这可以帮助。
| 归档时间: |
|
| 查看次数: |
1349 次 |
| 最近记录: |