技术文章 > [原创]C#提取EXCEL文件表格并自动生成HTML页面表格

[原创]C#提取EXCEL文件表格并自动生成HTML页面表格

2018-06-22 01:45

文档管理软件,文档管理系统,知识管理系统,档案管理系统的技术资料:

以下C#代码是自动从Excel文件提取数据(表格)并自动生成Html页面表格。

关键点一:
引用准确的控件(需要安装完整版本的OFFICE 2003),或安装OFFICE 2003 PIA模块(联高软件>FileBone有链接)。

关键点二:
using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;

// 这句话需要特别注意哦!
using Excel = Microsoft.Office.Interop.Excel;

namespace Legalsoft.Basic
{
public class Office_Interface
{
private static string Excel2Html(string fileName)
{
StringBuilder sb = new StringBuilder();
if (!File.Exists(fileName)) return “没有找到“ + fileName + “文件!“;
sb.AppendLine(“<!DOCTYPE HTML PUBLIC \“-//W3C//DTD HTML 4.0 Transitional//EN\“>“);
sb.AppendLine(“<html>“);
sb.AppendLine(“<head>“);
sb.AppendLine(“<title>“ + fileName + “</title>“);
sb.AppendLine(“<meta http-equiv=\“content-type\“ content=\“text/html; charset=gb2312\“ />“);
sb.AppendLine(“<meta name=\“generator\“ content=\“Codingrapg of LEgalsoft.com.cn\“>“);
sb.AppendLine(“</head>“);
sb.AppendLine(“<body>“);
Excel.Application excel = null;
Excel.Workbooks wbs = null;
Excel.Workbook wb = null;
Excel.Worksheet ws = null;
Excel.Range range1 = null;
object Nothing = System.Reflection.Missing.Value;
try
{
excel = new Excel.Application();
excel.UserControl = true;
excel.DisplayAlerts = false;
excel.Application.Workbooks.Open(fileName, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing);
wbs = excel.Workbooks;
wb = wbs[1];
for (int k = 0; k < wb.Worksheets.Count; k++)
{
ws = (Excel.Worksheet)wb.Worksheets[k + 1];
if (ws == null) break;
int rowCount = ws.UsedRange.Rows.Count;
int colCount = ws.UsedRange.Columns.Count;
if (rowCount < 2 || colCount < 2) break;
sb.AppendLine(“<table width=\“100%\“ cellpadding=0 cellspacing=0 border=1 bordercolor=\“#888888\“ style=\“border-collapse:collapse;padding:4px;\“>“);
for (int i = 0; i < rowCount; i++)
{
sb.AppendLine(“<tr>“);
for (int j = 0; j < colCount; j++)
{
range1 = ws.get_Range(ws.Cells[i + 1, j + 1], ws.Cells[i + 1, j + 1]);
if (range1 != null)
{
sb.AppendLine(“<td>“ + range1.Text + “</td>“);
}
else
{
sb.AppendLine(“<td></td>“);
}
}
sb.AppendLine(“</tr>“);
}
sb.AppendLine(“</table>“);
sb.AppendLine(“<br>“);
}
}
finally
{
if (excel != null)
{
if (wbs != null)
{
if (wb != null)
{
if (ws != null)
{
if (range1 != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(range1);
range1 = null;
}
System.Runtime.InteropServices.Marshal.ReleaseComObject(ws);
ws = null;
}
wb.Close(false, Nothing, Nothing);
System.Runtime.InteropServices.Marshal.ReleaseComObject(wb);
wb = null;
}
wbs.Close();
System.Runtime.InteropServices.Marshal.ReleaseComObject(wbs);
wbs = null;
}
excel.Application.Workbooks.Close();
excel.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
excel = null;
GC.Collect();
}
}
sb.AppendLine(“</body>“);
sb.AppendLine(“</html>“);
return sb.ToString();
}
}
}