.NET实现 导出带超链接的Excel数据
using File4._5.model; using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; using System; using System.Collections.Generic; using System.IO; using System.Windows.Forms; namespace File4._5 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btnRead_Click(object sender, EventArgs e) { var result = ""; try { bool isAll = ckAll.Checked; var fileModels = new List<FileModel>(); var folderPath = txtPath.Text.Trim(); var fileInfos = new List<FileInfo>(); if (isAll) { var folders = Directory.GetDirectories(folderPath); foreach (var folderStr in folders) { DirectoryInfo folder = new DirectoryInfo(folderStr); foreach (var file in folder.GetFiles()) { Console.WriteLine(file.FullName); result += file.FullName + Environment.NewLine; fileModels.Add(new FileModel() { file_name = file.Name, file_path = file.FullName }); ; } } } else { DirectoryInfo folder = new DirectoryInfo(folderPath); foreach (var file in folder.GetFiles()) { Console.WriteLine(file.FullName); result += file.FullName + Environment.NewLine; fileModels.Add(new FileModel() { file_name = file.Name, file_path = file.FullName }); ; } } Dictionary<string, string> thDic = new Dictionary<string, string>(); thDic.Add("file_name", "文件名"); thDic.Add("file_path", "文件路径"); var excelPath = folderPath + "/" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls"; // NPOIHelper.PageSaveToXls(excelPath, fileModels, thDic); var respSre = saveExecl(excelPath, fileModels); if (string.IsNullOrEmpty(respSre)) { txtShow.Text = ""; txtShow.Text = excelPath; MessageBox.Show("保存成功"); } else { MessageBox.Show("保存失败:" + respSre); } } catch (Exception ex) { result = "异常:" + ex.Message + Environment.NewLine + "代码:" + ex.StackTrace; } Console.Read(); } private string saveExecl(string path, List<FileModel> list) { //excel IWorkbook book = null; //excel的sheet页 ISheet sheet = null; try { using (FileStream stream = new FileStream(path, FileMode.Create, FileAccess.ReadWrite)) { //扩展名 string extension = Path.GetExtension(path); switch (extension.ToLower()) { case ".xls": book = new HSSFWorkbook();//NPOI.dll break; case ".xlsx": book = new XSSFWorkbook();//NPOI.OOXML.dll break; } sheet = book.CreateSheet(); //设置表头 var header = sheet.CreateRow(0); header.CreateCell(0).SetCellValue("文件名称"); header.CreateCell(1).SetCellValue("文件路径"); //创建表的内容 var trIndex = 1; list.ForEach(i => { HSSFHyperlink link = new HSSFHyperlink(HyperlinkType.Url); link.Address = i.file_path; var tr = sheet.CreateRow(trIndex); tr.CreateCell(0).SetCellValue(i.file_name); var cellName = tr.CreateCell(0); cellName.SetCellValue(i.file_name); cellName.Hyperlink = link; var cell = tr.CreateCell(1); cell.SetCellValue(i.file_path); // cell.Hyperlink = link; trIndex++; }); book.Write(stream); stream.Close(); } return ""; } catch (Exception ex) { return ex.Message; } } } }
model 类
public class FileModel { public string file_name { get; set; } public string file_path { get; set; } }