2011-02-23 40 views
0

我正在使用以下代码将数据库中的多个表的数据输出到Excel文档。iTextSharp EXCEL输出

Protected void btnExcelExport_Click(object sender, EventArgs e) 
{ 

string strQuery = "SELECT s.Story, s.StoryCategoryID, CONVERT(VARCHAR(10), 
s.CreationDate, 103) AS CreationDate, m.CompanyRole, af.Name FROM Story s INNER JOIN  
ProjectIterationMember pm ON pm.ProjectIterationMemberID = s.ProjectIterationMemberID 
INNER JOIN Iterations i ON i.ProjectIterationID = pm.ProjectIterationID INNER JOIN 
Member m ON m.MemberID = pm.MemberID INNER JOIN ProjectStoryFactors psf ON psf.StoryID = 
s.StoryID INNER JOIN AgileFactors af ON af.AgileFactorID = psf.AgileFactorID WHERE 
i.ProjectID = '" + proj_id + "'"; 

SqlCommand cmd = new SqlCommand(strQuery); 
DataTable dt = GetData(cmd); 

GridView GridView1 = new GridView(); 
GridView1.AllowPaging = false; 
GridView1.DataSource = dt; 
GridView1.DataBind(); 

Response.Clear(); 
Response.Buffer = true; 
Response.AddHeader("content-disposition","attachment;filename=RetroCloud" + 
DateTime.Now.Ticks + ".xls"); 
Response.Charset = ""; 
Response.ContentType = "application/vnd.ms-excel"; 
StringWriter sw = new StringWriter(); 
HtmlTextWriter hw = new HtmlTextWriter(sw); 

for (int i = 0; i < GridView1.Rows.Count; i++) 
{ 

    GridView1.Rows[i].Attributes.Add("class", "textmode"); 
} 
GridView1.RenderControl(hw); 

string style = @"<style> .textmode { mso-number-format:\@; } </style>"; 
Response.Write(style); 
Response.Output.Write(sw.ToString()); 
Response.Flush(); 
Response.End(); 
} 

输出如下:

Story | StoryCategoryID | CreationDate | CompanyRole | Name 

negative iii | 1 | 21/02/2011 | Business Analyst | Project Duration 
negative iii | 1 | 21/02/2011 | Business Analyst | Team Size 
negative iii | 1 | 21/02/2011 | Business Analyst | Process 
negative ccc | 1 | 22/02/2011 | Admin | Workspace Layout 
negative ccc | 1 | 22/02/2011 | Admin | Organisational and Reporting Structure 
negative ccc | 1 | 22/02/2011 | Admin | Process 

我希望做的是三两件事。非常感谢您的帮助!

1)更改显式来自数据库字段(即从StoryCategoryID到Story Type)的标题名称, 2)对于StoryCategoryID,如果检索到1,则显示'Negative',如果检索到0,则显示而是积极的。 3)在下列格式输出:

Story | Story Type | Creation Date | Company Role | Tag 1 | Tag 2 | Tag 3 

negative iii | 1 | 21/02/2011 | Business Analyst | Project Duration | Team Size | Process 
negative ccc | 1 | 22/02/2011 | Admin | Workspace Layout | Organisational | Process 

回答

1

您可以修改数据表中的列名。使用foreach(DataColumn col in dt.Columns)然后使用col.ColumnName

您可以在循环内使用(Convert.ToInt16(col[n]) != 1)? "Positive" : "Negative"访问和修改标准的特定列的数据。为环路条件使用dt.Rows.Count

希望这会有所帮助。

if (col.ColumnName == "StoryCategoryId") //Or "Story Type" 
for(int rowCount = 0; rowCount < table.Rows.Count; rowCount++) 
{ 
    col[rowCount] = (Convert.ToInt16(col[rowCount]) == 0) ? "Positive" : "Negative"; 
} 
+0

你能告诉我如何修改使用循环列数据:

您可以将foreach循环内使用它?谢谢!我想得到积极的,负面的工作:) – MiziaQ 2011-02-23 20:05:39

+0

请参阅我的编辑。 – KaeL 2011-02-24 05:52:05