您的位置:首页 > 其它

从Excel读取数据绘制GridView的例子

2015-03-26 09:17 288 查看
工作原因,需要设计一个读取Excel并按照源文件中格式设定GridView的页面,因此需要考虑到Excel中合并单元格与GridView匹配.

尝试了很多办法,发现只有在触发OnRowCreated事件时重新绘制才能让实际显示页面达到预期效果,现附上前台代码:

etc...
<asp:GridView ID="GridView1" runat="server" width="100%" AllowPaging="True" PageSize="20" <span style="color:#ffffff;background-color: rgb(255, 102, 102);">OnRowCreated="GridView1_RowCreated"</span> />
etc...
要触发此事件,需要在后台绑定控件数据:

// 页面载入事件
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string filePath = Server.MapPath(upload_path+file_name);
showClean();
if (File.Exists(filePath))
{
showText("今日已上传");
DataTable dt = GetExcelNpoi.getDataTable(filePath,0);
<span style="background-color: rgb(51, 204, 255);">dt.Rows.RemoveAt(0);</span>// 删除一行以保证表头一致
<span style="color:#ffffff;background-color: rgb(255, 102, 102);">GridView1.DataSource = dt;</span>
<span style="background-color: rgb(255, 102, 102);"><span style="color:#ffffff;">GridView1.DataBind();</span></span>
}
else
{
showText("今日未上传");
}
}
}
这里删除一行的原因是,在表头绘制中,只能操作一行表头,而且换行也是用"</th></tr><tr>"直接写入表头文本中的,所以没有被操作的表头需要删掉以避免绘图混乱.本例绘制的是2行表头,因此删除一行

protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
int sheetIndex = 0;// 表序号
int headerRowCount = 2;// 表头行数
string filePath = Server.MapPath(upload_path+file_name);

// 判断创建的行是否为表头行
if (e.Row.RowType == DataControlRowType.Header)
{
// 获取表头所在行的所有单元格
<span style="background-color: rgb(255, 102, 102);"><span style="color:#ffffff;">TableCellCollection rows = e.Row.Cells;</span></span>
HSSFWorkbook workbook = GetExcelNpoi.openWorkbook(filePath);
ISheet sheet = GetExcelNpoi.openSheet(workbook,sheetIndex);// 打开第一个表
// 绘制表头
rows.Clear();
int count = 0;
for (int i = 0; i < headerRowCount; i++)
{
for (int j = 0; j < sheet.GetRow(i).LastCellNum; j++)
{
int rowIndex = i,colIndex = j;
int rowSpan = 0,colSpan = 0;
int rowNum = rowIndex + 1,colNum = colIndex + 1;
bool isMerged,isHeader;
GetExcelNpoi.getCellInfo(sheet,rowNum,colNum,out rowSpan,out colSpan,out isMerged,out isHeader);
if ((isMerged && isHeader) || (!isMerged && !isHeader))
{
rows.Add(new TableHeaderCell());
rows[count].RowSpan = rowSpan;
rows[count].ColumnSpan = colSpan;
rows[count].Text = sheet.GetRow(rowIndex).GetCell(colIndex).ToString();
count++;
}
}
<span style="background-color: rgb(51, 204, 255);">rows[count-1].Text += "</th></tr><tr>";// 添加行尾</span>
}
}
}
涂红位置表明,对单行进行操作,涂蓝位置则说明在绘制完毕一行后,需要用html脚本语言添加行尾

(注:GetExcelNpoi类是我自己写的操作excel的功能类,详情请见另一篇博客http://blog.csdn.net/fireghost57/article/details/25623143 用到了NPOI,需要手动网上下载)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息