a250152吧 关注:7贴子:212
  • 0回复贴,共1

C# 读取excel

只看楼主收藏回复

protected void Button1_Click(object sender, EventArgs e)
{
string strName = FileUpload1.FileName;
string
strPath=Server.MapPath("/UploadFiles/"+FileUpload1.FileName);
FileUpload1.SaveAs(strPath);
if (File.Exists(strPath))
{
//根据路径通过已存在的excel来创建HSSFWorkbook,即整个excel文档
FileStream file = new FileStream(strPath, FileMode.Open,
FileAccess.Read);
HSSFWorkbook workbook = new HSSFWorkbook(file);
//获取excel的第一个sheet
Sheet sheet = workbook.GetSheet("员工组");
DataTable table = new DataTable();
//获取sheet的首行
Row headerRow = sheet.GetRow(0);
//一行最后一个方格的编号 即总的列数
int cellCount = headerRow.LastCellNum;
for (int i = headerRow.FirstCellNum; i < cellCount;
i++)
{
DataColumn column = new
DataColumn(headerRow.GetCell(i).StringCellValue);
table.Columns.Add(column);
}
//最后一列的标号 即总的行数
int rowCount = sheet.LastRowNum;
for (int i = (sheet.FirstRowNum + 1); i <
sheet.LastRowNum; i++)
{
Row row = sheet.GetRow(i);
DataRow dataRow = table.NewRow();
for (int j = row.FirstCellNum; j < cellCount; j++)
{
if (row.GetCell(j) != null)
dataRow[j] = row.GetCell(j).ToString();
}
table.Rows.Add(dataRow);
}
workbook = null;
sheet = null;
StringBuilder str=new StringBuilder("<table>");
str.Append("<tr>");
for (int i = 0; i < table.Columns.Count; i++)
{
str.Append("<td>"+table.Columns[i].ColumnName+"</td>");
}
str.Append("</tr>");
for (int i = 0; i < table.Rows.Count; i++)
{
str.Append("<tr>");
for (int j = 0; j < table.Columns.Count; j++)
{
str.Append("<td>" +
table.Rows[i][j].ToString()+ "</td>");
}
str.Append("</tr>");
}
str.Append("</table>");
Response.Write(str.ToString());
Response.Write(table.Rows.Count.ToString());
}
}


IP属地:辽宁1楼2011-12-23 06:32回复