C#使用Spire.XLS for .NET實現(xiàn)將網(wǎng)頁數(shù)據(jù)一鍵導出為Excel
在Web開發(fā)和數(shù)據(jù)處理中,C# HTML to Excel轉(zhuǎn)換需求頻現(xiàn)。網(wǎng)頁表格數(shù)據(jù)手動復(fù)制到Excel常導致樣式丟失、格式混亂,費時費力。隨著Web爬取數(shù)據(jù)自動化趨勢,高效實現(xiàn)HTML 到 XLS/XLSX的轉(zhuǎn)換成為剛需。本文分享基于Spire.XLS for .NET的實用方案,支持HTML5表格解析,保留復(fù)雜樣式。
需求背景與痛點分析
Web應(yīng)用或爬蟲常輸出HTML表格,但直接導入Excel易遇兼容性問題。傳統(tǒng)方法如手動復(fù)制或瀏覽器導出,效率低且樣式丟失嚴重。新趨勢下,C#程序化處理Web數(shù)據(jù)(如報表、統(tǒng)計表)需求激增。痛點包括:復(fù)雜嵌套表格解析難、CSS樣式不保留、大文件性能瓶頸。
推薦方案: Spire.XLS for .NET
Spire.XLS for .NET 是高效Excel操作庫,其社區(qū)版免費,支持C# HTML to Excel的直接轉(zhuǎn)換。優(yōu)勢在于解析HTML5復(fù)雜結(jié)構(gòu),保留表格樣式、顏色、邊框等。
| 庫名稱 | HTML支持度 | 樣式保留 | .NET 8兼容 | 免費版限制 |
|---|---|---|---|---|
| Spire.XLS | 高(HTML5) | 優(yōu)秀 | 是 | 社區(qū)版5頁 |
| NPOI | 低 | 一般 | 是 | 完全免費 |
| ClosedXML | 無直接支持 | 優(yōu)秀 | 是 | 完全免費 |
Spire.XLS勝在開箱即用,無需額外HTML解析庫如HtmlAgilityPack。
實戰(zhàn)步驟與代碼示例
實現(xiàn)HTML 到 XLS/XLSX的轉(zhuǎn)換僅需3步:
- NuGet安裝:
Install-Package Spire.XLS -Version 13.4.3(最新版支持.NET 8)。 - 加載HTML并轉(zhuǎn)換:使用
LoadFromHtml方法。 - 保存Excel:輸出XLSX格式。
using Spire.Xls;
class Program
{
static void Main()
{
// 創(chuàng)建工作簿
Workbook workbook = new Workbook();
// 加載HTML文件(支持文件路徑或HTML字符串)
string htmlFilePath = "input.html";
workbook.LoadFromHtml(htmlFilePath);
// 保存為Excel文件(XLSX格式)
string outputFilePath = "output.xlsx";
workbook.SaveToFile(outputFilePath, ExcelVersion.Version2013);
workbook.Dispose();
}
}
輸入HTML示例(復(fù)雜表格):
<table border="1">
<tr><th>產(chǎn)品</th><th>銷量</th></tr>
<tr><td>手機</td><td style="color:red;">1000</td></tr>
</table>輸出Excel效果:表格樣式、顏色完整保留。
常見問題與優(yōu)化
- 大文件處理:社區(qū)版限5頁,商用升級專業(yè)版。優(yōu)化:預(yù)解析HTML分批加載。
- HTML字符串輸入:用
workbook.LoadFromHtml(htmlString)直接轉(zhuǎn)換。 - 異常處理:包裹try-catch,檢查HTML語法。
- 性能提示:NET 8下多線程安全,適合批量Web數(shù)據(jù)導出。
知識擴展
下面小編就和大家簡單講講C#將HTML轉(zhuǎn)Excel的其他方法
1.C# HTML轉(zhuǎn)EXCEL
private void ToExcel(string html)
{
Response.ContentType = "application/force-download";
Response.AddHeader("content-disposition",
"attachment; filename=" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls");
Response.Write("<html xmlns:x=\"urn:schemas-microsoft-com:office:excel\">");
Response.Write("<head>");
Response.Write("<META http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">");
string fileCss = Server.MapPath("~/UI/themes/DRP.UI.Ext.css");
string cssText = string.Empty;
StreamReader sr = new StreamReader(fileCss);
var line = string.Empty;
while ((line = sr.ReadLine()) != null)
{
cssText += line;
}
sr.Close();
Response.Write("<style>" + cssText + "</style>");
Response.Write("<!--[if gte mso 9]><xml>");
Response.Write("<x:ExcelWorkbook>");
Response.Write("<x:ExcelWorksheets>");
Response.Write("<x:ExcelWorksheet>");
Response.Write("<x:Name>Report Data</x:Name>");
Response.Write("<x:WorksheetOptions>");
Response.Write("<x:Print>");
Response.Write("<x:ValidPrinterInfo/>");
Response.Write("</x:Print>");
Response.Write("</x:WorksheetOptions>");
Response.Write("</x:ExcelWorksheet>");
Response.Write("</x:ExcelWorksheets>");
Response.Write("</x:ExcelWorkbook>");
Response.Write("</xml>");
Response.Write("<![endif]--> ");
Response.Write(html);//HTML
Response.Flush();
Response.End();
}2.C#/VB.NET:將 HTML 轉(zhuǎn)換為 Excel
using Spire.Xls;
namespace ConvertHtmlToExcel
{
internal class Program
{
static void Main(string[] args)
{
// 確定輸入HTML文件地址
string filePath = @"C:\Users\Administrator\Desktop\Sample.html";
// 創(chuàng)建一個 Workbook 實例
Workbook workbook = new Workbook();
// 加載 HTML 文件
workbook.LoadFromHtml(filePath);
// 將HTML文件保存為Excel文件格式
string result = @"C:\Users\Administrator\Desktop\ToExcel.xlsx";
workbook.SaveToFile(result, ExcelVersion.Version2013);
workbook.Dispose();
}
}
}3.c# 把excel轉(zhuǎn)換html
private DataTable GetTableFromExcel()
{
DataTable dt = new DataTable();
try
{
if (exclFileUpload.HasFile)
{
string FileName = Path.GetFileName(exclFileUpload.PostedFile.FileName);
string Extension = Path.GetExtension(exclFileUpload.PostedFile.FileName);
string FolderPath = Server.MapPath(ConfigurationManager.AppSettings["FolderPath"]);
//string NewFileName = string.Format("{0}_{1}",DateTime.Now.ToString().Replace("/","").Replace(" ","").Replace(":",""),FileName);
string FilePath = Path.Combine(string.Format("{0}/{1}",FolderPath,FileName));
exclFileUpload.SaveAs(FilePath);
string conStr = "";
switch (Extension)
{
case ".xls": //Excel 97-03
conStr = ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString;
break;
case ".xlsx": //Excel 07
conStr = ConfigurationManager.ConnectionStrings["Excel07ConString"].ConnectionString;
break;
}
conStr = String.Format(conStr,FilePath,true);
OleDbConnection connExcel = new OleDbConnection(conStr);
OleDbCommand cmdExcel = new OleDbCommand();
OleDbDataAdapter oda = new OleDbDataAdapter();
cmdExcel.Connection = connExcel;
connExcel.Open();
DataTable dtExcelSchema;
dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,null);
string SheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
connExcel.Close();
connExcel.Open();
cmdExcel.CommandText = "SELECT * From [" + SheetName + "]";
oda.SelectCommand = cmdExcel;
oda.Fill(dt);
connExcel.Close();
File.Delete(FilePath);
}
}
catch (Exception ex)
{
}
return dt;
}總結(jié)
將HTML內(nèi)容轉(zhuǎn)換為Excel是數(shù)據(jù)處理中的常見需求。Spire.XLS for .NET 提供簡潔的API,支持將HTML表格及其樣式直接轉(zhuǎn)換為XLS/XLSX格式。開發(fā)者無需手動解析網(wǎng)頁數(shù)據(jù),幾行代碼即可完成批量轉(zhuǎn)換,適用于數(shù)據(jù)采集、報表生成等場景,且不依賴Microsoft Office環(huán)境。試試這個免費社區(qū)版,高效解決樣式丟失痛點。
到此這篇關(guān)于C#使用Spire.XLS for .NET實現(xiàn)將網(wǎng)頁數(shù)據(jù)一鍵導出為Excel的文章就介紹到這了,更多相關(guān)C#網(wǎng)頁數(shù)據(jù)導出為Excel內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C#實現(xiàn)托盤程序并禁止多個應(yīng)用實例運行的方法
這篇文章主要介紹了C#實現(xiàn)托盤程序并禁止多個應(yīng)用實例運行的方法,涉及C#中NotifyIcon控件的使用及設(shè)置標志位控制程序只運行一個的實現(xiàn)技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-11-11
C#實現(xiàn)根據(jù)給出的相對地址獲取網(wǎng)站絕對地址的方法
這篇文章主要介紹了C#實現(xiàn)根據(jù)給出的相對地址獲取網(wǎng)站絕對地址的方法,涉及C#URL及字符串操作的技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-03-03
C#啟動windows服務(wù)方法的相關(guān)問題分析
C#啟動windows服務(wù)的方法都是什么呢?C#啟動服務(wù)類型為Disabled的windows服務(wù)會遇到什么樣的問題呢?那么本文就向你介紹C#啟動windows服務(wù)的方法的相關(guān)內(nèi)容2012-12-12

