C#使用Spire.XLS for .NET實(shí)現(xiàn)將網(wǎng)頁(yè)數(shù)據(jù)一鍵導(dǎo)出為Excel
在Web開(kāi)發(fā)和數(shù)據(jù)處理中,C# HTML to Excel轉(zhuǎn)換需求頻現(xiàn)。網(wǎng)頁(yè)表格數(shù)據(jù)手動(dòng)復(fù)制到Excel常導(dǎo)致樣式丟失、格式混亂,費(fèi)時(shí)費(fèi)力。隨著Web爬取數(shù)據(jù)自動(dòng)化趨勢(shì),高效實(shí)現(xiàn)HTML 到 XLS/XLSX的轉(zhuǎn)換成為剛需。本文分享基于Spire.XLS for .NET的實(shí)用方案,支持HTML5表格解析,保留復(fù)雜樣式。
需求背景與痛點(diǎn)分析
Web應(yīng)用或爬蟲(chóng)常輸出HTML表格,但直接導(dǎo)入Excel易遇兼容性問(wèn)題。傳統(tǒng)方法如手動(dòng)復(fù)制或?yàn)g覽器導(dǎo)出,效率低且樣式丟失嚴(yán)重。新趨勢(shì)下,C#程序化處理Web數(shù)據(jù)(如報(bào)表、統(tǒng)計(jì)表)需求激增。痛點(diǎn)包括:復(fù)雜嵌套表格解析難、CSS樣式不保留、大文件性能瓶頸。
推薦方案: Spire.XLS for .NET
Spire.XLS for .NET 是高效Excel操作庫(kù),其社區(qū)版免費(fèi),支持C# HTML to Excel的直接轉(zhuǎn)換。優(yōu)勢(shì)在于解析HTML5復(fù)雜結(jié)構(gòu),保留表格樣式、顏色、邊框等。
| 庫(kù)名稱 | HTML支持度 | 樣式保留 | .NET 8兼容 | 免費(fèi)版限制 |
|---|---|---|---|---|
| Spire.XLS | 高(HTML5) | 優(yōu)秀 | 是 | 社區(qū)版5頁(yè) |
| NPOI | 低 | 一般 | 是 | 完全免費(fèi) |
| ClosedXML | 無(wú)直接支持 | 優(yōu)秀 | 是 | 完全免費(fèi) |
Spire.XLS勝在開(kāi)箱即用,無(wú)需額外HTML解析庫(kù)如HtmlAgilityPack。
實(shí)戰(zhàn)步驟與代碼示例
實(shí)現(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>手機(jī)</td><td style="color:red;">1000</td></tr>
</table>輸出Excel效果:表格樣式、顏色完整保留。
常見(jiàn)問(wèn)題與優(yōu)化
- 大文件處理:社區(qū)版限5頁(yè),商用升級(jí)專業(yè)版。優(yōu)化:預(yù)解析HTML分批加載。
- HTML字符串輸入:用
workbook.LoadFromHtml(htmlString)直接轉(zhuǎn)換。 - 異常處理:包裹try-catch,檢查HTML語(yǔ)法。
- 性能提示:NET 8下多線程安全,適合批量Web數(shù)據(jù)導(dǎo)出。
知識(shí)擴(kuò)展
下面小編就和大家簡(jiǎn)單講講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)建一個(gè) Workbook 實(shí)例
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ù)處理中的常見(jiàn)需求。Spire.XLS for .NET 提供簡(jiǎn)潔的API,支持將HTML表格及其樣式直接轉(zhuǎn)換為XLS/XLSX格式。開(kāi)發(fā)者無(wú)需手動(dòng)解析網(wǎng)頁(yè)數(shù)據(jù),幾行代碼即可完成批量轉(zhuǎn)換,適用于數(shù)據(jù)采集、報(bào)表生成等場(chǎng)景,且不依賴Microsoft Office環(huán)境。試試這個(gè)免費(fèi)社區(qū)版,高效解決樣式丟失痛點(diǎn)。
到此這篇關(guān)于C#使用Spire.XLS for .NET實(shí)現(xiàn)將網(wǎng)頁(yè)數(shù)據(jù)一鍵導(dǎo)出為Excel的文章就介紹到這了,更多相關(guān)C#網(wǎng)頁(yè)數(shù)據(jù)導(dǎo)出為Excel內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C#實(shí)現(xiàn)托盤程序并禁止多個(gè)應(yīng)用實(shí)例運(yùn)行的方法
這篇文章主要介紹了C#實(shí)現(xiàn)托盤程序并禁止多個(gè)應(yīng)用實(shí)例運(yùn)行的方法,涉及C#中NotifyIcon控件的使用及設(shè)置標(biāo)志位控制程序只運(yùn)行一個(gè)的實(shí)現(xiàn)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-11-11
C#實(shí)現(xiàn)根據(jù)給出的相對(duì)地址獲取網(wǎng)站絕對(duì)地址的方法
這篇文章主要介紹了C#實(shí)現(xiàn)根據(jù)給出的相對(duì)地址獲取網(wǎng)站絕對(duì)地址的方法,涉及C#URL及字符串操作的技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-03-03
簡(jiǎn)介Winform中創(chuàng)建用戶控件
用戶控件可以讓開(kāi)發(fā)人員對(duì)VS控件進(jìn)行組裝。下面我們來(lái)創(chuàng)建一個(gè)按鈕的用戶控件我們可以給它添加屬性,并且添加相應(yīng)鼠標(biāo)移入、移出事件。2013-03-03
C#啟動(dòng)windows服務(wù)方法的相關(guān)問(wèn)題分析
C#啟動(dòng)windows服務(wù)的方法都是什么呢?C#啟動(dòng)服務(wù)類型為Disabled的windows服務(wù)會(huì)遇到什么樣的問(wèn)題呢?那么本文就向你介紹C#啟動(dòng)windows服務(wù)的方法的相關(guān)內(nèi)容2012-12-12
C#使用NPOI實(shí)現(xiàn)Excel導(dǎo)入導(dǎo)出功能
這篇文章主要為大家詳細(xì)介紹了C#使用NPOI實(shí)現(xiàn)Excel導(dǎo)入導(dǎo)出功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-02-02

