csharp: Export DataTable to Excel using OpenXml 2.5 in asp.net

2023-10-31

 /// <summary>
    /// 
    /// </summary>
    public partial class WebForm1 : System.Web.UI.Page
    {


        DataTable getData()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("id", typeof(int));
            dt.Columns.Add("name", typeof(string));
            dt.Rows.Add(1, "geovindu");
            dt.Rows.Add(2, "geov");
            dt.Rows.Add(3, "塗斯博");
            dt.Rows.Add(4, "趙雅芝");
            dt.Rows.Add(5, " なわち日本語");
            dt.Rows.Add(6, "처리한다");
            dt.Rows.Add(7, "涂聚文");
            dt.Rows.Add(8, "塗聚文");
            return dt;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindGrid();
            }

        }
        /// <summary>
        /// 
        /// </summary>
        private void BindGrid()
        {
            this.GridView1.DataSource = getData();
            GridView1.DataBind();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Button1_Click(object sender, EventArgs e)
        {
            
            string rootPath = HttpContext.Current.Server.MapPath("~").ToString();
            string localCopy = "塗聚文" + DateTime.Now.ToString("yyyyMMddHHmmssfff")+ ".xlsx"; //
            string file = new ExcelHelper().ExportToExcel(getData(), "geovindu",localCopy);
            File.Copy(file, rootPath + localCopy);
            Response.Redirect(HttpUtility.UrlEncode(localCopy,System.Text.Encoding.UTF8));
        }
    }


//https://www.microsoft.com/en-us/download/details.aspx?id=5124  Open XML SDK 2.0 for Microsoft Office
   //https://www.microsoft.com/en-us/download/details.aspx?id=30425 Open XML SDK 2.5 for Microsoft Office
   //https://github.com/OfficeDev/Open-Xml-Sdk
   //http://www.codeproject.com/Tips/366446/Export-GridView-Data-to-Excel-using-OpenXml
 
   //引用: WindowsBase.DLL  C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\WindowsBase.dll
 
   /// <summary>
   ///
   /// </summary>
   internal class ExcelHelper
   {
 
       /// <summary>
       ///
       /// </summary>
       internal class ColumnCaption
       {
           private static string[] Alphabets = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
           private static ColumnCaption instance = null;
           private List<string> cellHeaders = null;
           public static ColumnCaption Instance
           {
               get
               {
                   if (instance == null)
                       return new ColumnCaption();
                   else return ColumnCaption.Instance;
               }
           }
           /// <summary>
           ///
           /// </summary>
           public ColumnCaption()
           {
               this.InitCollection();
           }
           /// <summary>
           ///
           /// </summary>
           private void InitCollection()
           {
               cellHeaders = new List<string>();
 
               foreach (string sItem in Alphabets)
                   cellHeaders.Add(sItem);
 
               foreach (string item in Alphabets)
                   foreach (string sItem in Alphabets)
                       cellHeaders.Add(item + sItem);
           }
 
           /// <summary>
           /// Returns the column caption for the given row & column index.
           /// </summary>
           /// <param name="rowIndex">Index of the row.</param>
           /// <param name="columnIndex">Index of the column.</param>
           /// <returns></returns>
           internal string Get(int rowIndex, int columnIndex)
           {
               return this.cellHeaders.ElementAt(columnIndex) + (rowIndex + 1).ToString();
           }
       }
 
       /// <summary>
       /// 导出
       /// </summary>
       /// <param name="DataTable">DataTable</param>
       /// <param name="sheetname">工作表名</param>
       /// <param name="filename">文件名</param>
       /// <returns></returns>
       internal string ExportToExcel(DataTable table, string sheetname,string filename)
       {
           string excelfile = Path.GetTempPath() + filename;
           using (SpreadsheetDocument excelDoc = SpreadsheetDocument.Create(excelfile, DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook))
           {
               CreateExcelParts(excelDoc, table,sheetname);
           }
           return excelfile;
       }
       /// <summary>
       ///
       /// </summary>
       /// <param name="spreadsheetDoc"></param>
       /// <param name="data"></param>
       /// <param name="sheetname"></param>
       private void CreateExcelParts(SpreadsheetDocument spreadsheetDoc, DataTable data,string sheetname)
       {
           WorkbookPart workbookPart = spreadsheetDoc.AddWorkbookPart();
           CreateWorkbookPart(workbookPart, sheetname);
 
           int workBookPartCount = 1;
 
           WorkbookStylesPart workbookStylesPart = workbookPart.AddNewPart<WorkbookStylesPart>("rId" + (workBookPartCount++).ToString());
           CreateWorkbookStylesPart(workbookStylesPart);
 
           WorksheetPart worksheetPart = workbookPart.AddNewPart<WorksheetPart>("rId" + (101).ToString());
           CreateWorksheetPart(workbookPart.WorksheetParts.ElementAt(0), data);
 
           SharedStringTablePart sharedStringTablePart = workbookPart.AddNewPart<SharedStringTablePart>("rId" + (workBookPartCount++).ToString());
           CreateSharedStringTablePart(sharedStringTablePart, data);
 
           workbookPart.Workbook.Save();
       }
 
       /// <summary>
       /// Creates the shared string table part.
       /// </summary>
       /// <param name="sharedStringTablePart">The shared string table part.</param>
       /// <param name="sheetData">The sheet data.</param>
       private void CreateSharedStringTablePart(SharedStringTablePart sharedStringTablePart, DataTable sheetData)
       {
           UInt32Value stringCount = Convert.ToUInt32(sheetData.Rows.Count) + Convert.ToUInt32(sheetData.Columns.Count);
 
           SharedStringTable sharedStringTable = new SharedStringTable()
           {
               Count = stringCount,
               UniqueCount = stringCount
           };
 
           for (int columnIndex = 0; columnIndex < sheetData.Columns.Count; columnIndex++)
           {
               SharedStringItem sharedStringItem = new SharedStringItem();
               Text text = new Text();
               text.Text = sheetData.Columns[columnIndex].ColumnName;
               sharedStringItem.Append(text);
               sharedStringTable.Append(sharedStringItem);
           }
 
           for (int rowIndex = 0; rowIndex < sheetData.Rows.Count; rowIndex++)
           {
               SharedStringItem sharedStringItem = new SharedStringItem();
               Text text = new Text();
               text.Text = sheetData.Rows[rowIndex][0].ToString();
               sharedStringItem.Append(text);
               sharedStringTable.Append(sharedStringItem);
           }
 
           sharedStringTablePart.SharedStringTable = sharedStringTable;
       }
 
       /// <summary>
       /// Creates the worksheet part.
       /// </summary>
       /// <param name="worksheetPart">The worksheet part.</param>
       /// <param name="data">The data.</param>
       private void CreateWorksheetPart(WorksheetPart worksheetPart, DataTable data)
       {
           Worksheet worksheet = new Worksheet() { MCAttributes = new MarkupCompatibilityAttributes() { Ignorable = "x14ac" } };
           worksheet.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
           worksheet.AddNamespaceDeclaration("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006");
           worksheet.AddNamespaceDeclaration("x14ac", "http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac");
 
 
           SheetViews sheetViews = new SheetViews();
           SheetView sheetView = new SheetView() { WorkbookViewId = (UInt32Value)0U };
           Selection selection = new Selection() { ActiveCell = "A1" };
           sheetView.Append(selection);
           sheetViews.Append(sheetView);
 
           PageMargins pageMargins = new PageMargins()
           {
               Left = 0.7D,
               Right = 0.7D,
               Top = 0.75D,
               Bottom = 0.75D,
               Header = 0.3D,
               Footer = 0.3D
           };
 
           SheetFormatProperties sheetFormatPr = new SheetFormatProperties()
           {
               DefaultRowHeight = 15D,
               DyDescent = 0.25D
           };
 
           SheetData sheetData = new SheetData();
 
           UInt32Value rowIndex = 1U;
 
           Row row1 = new Row()
           {
               RowIndex = rowIndex++,
               Spans = new ListValue<StringValue>() { InnerText = "1:3" },
               DyDescent = 0.25D
           };
 
           for (int columnIndex = 0; columnIndex < data.Columns.Count; columnIndex++)
           {
               Cell cell = new Cell() { CellReference = ExcelHelper.ColumnCaption.Instance.Get((Convert.ToInt32((UInt32)rowIndex) - 2), columnIndex), DataType = CellValues.String };
               CellValue cellValue = new CellValue();
               cellValue.Text = data.Columns[columnIndex].ColumnName.ToString().FormatCode();
               cell.Append(cellValue);
 
               row1.Append(cell);
           }
           sheetData.Append(row1);
 
           for (int rIndex = 0; rIndex < data.Rows.Count; rIndex++)
           {
               Row row = new Row()
               {
                   RowIndex = rowIndex++,
                   Spans = new ListValue<StringValue>() { InnerText = "1:3" },
                   DyDescent = 0.25D
               };
 
               for (int cIndex = 0; cIndex < data.Columns.Count; cIndex++)
               {
                   if (cIndex == 0)
                   {
                       Cell cell = new Cell() { CellReference = ExcelHelper.ColumnCaption.Instance.Get((Convert.ToInt32((UInt32)rowIndex) - 2), cIndex), DataType = CellValues.String };
                       CellValue cellValue = new CellValue();
                       cellValue.Text = data.Rows[rIndex][cIndex].ToString();
                       cell.Append(cellValue);
 
                       row.Append(cell);
                   }
                   else
                   {
                       Cell cell = new Cell() { CellReference = ExcelHelper.ColumnCaption.Instance.Get((Convert.ToInt32((UInt32)rowIndex) - 2), cIndex), DataType = CellValues.String };
                       CellValue cellValue = new CellValue();
                       cellValue.Text = data.Rows[rIndex][cIndex].ToString();
                       cell.Append(cellValue);
 
                       row.Append(cell);
                   }
               }
               sheetData.Append(row);
           }
 
           worksheet.Append(sheetViews);
           worksheet.Append(sheetFormatPr);
           worksheet.Append(sheetData);
           worksheet.Append(pageMargins);
           worksheetPart.Worksheet = worksheet;
       }
 
       /// <summary>
       /// Creates the workbook styles part.
       /// </summary>
       /// <param name="workbookStylesPart">The workbook styles part.</param>
       private void CreateWorkbookStylesPart(WorkbookStylesPart workbookStylesPart)
       {
           Stylesheet stylesheet = new Stylesheet() { MCAttributes = new MarkupCompatibilityAttributes() { Ignorable = "x14ac" } };
           stylesheet.AddNamespaceDeclaration("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006");
           stylesheet.AddNamespaceDeclaration("x14ac", "http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac");
 
           StylesheetExtensionList stylesheetExtensionList = new StylesheetExtensionList();
           StylesheetExtension stylesheetExtension = new StylesheetExtension() { Uri = "{EB79DEF2-80B8-43e5-95BD-54CBDDF9020C}" };
           stylesheetExtension.AddNamespaceDeclaration("x14", "http://schemas.microsoft.com/office/spreadsheetml/2009/9/main");
           DocumentFormat.OpenXml.Office2010.Excel.SlicerStyles slicerStyles = new DocumentFormat.OpenXml.Office2010.Excel.SlicerStyles() { DefaultSlicerStyle = "SlicerStyleLight1" };
           stylesheetExtension.Append(slicerStyles);
           stylesheetExtensionList.Append(stylesheetExtension);
 
           stylesheet.Append(stylesheetExtensionList);
 
           workbookStylesPart.Stylesheet = stylesheet;
       }
 
       /// <summary>
       /// Creates the workbook part.
       /// </summary>
       /// <param name="workbookPart">The workbook part.</param>
       private void CreateWorkbookPart(WorkbookPart workbookPart,string sheetName)
       {
           Workbook workbook = new Workbook();
           Sheets sheets = new Sheets();
 
           Sheet sheet = new Sheet()
           {
               Name = sheetName,  //工作表名
               SheetId = Convert.ToUInt32(101),
               Id = "rId" + (101).ToString()
           };
           sheets.Append(sheet);
 
           CalculationProperties calculationProperties = new CalculationProperties()
           {
               CalculationId = (UInt32Value)123456U  // some default Int32Value
           };
 
           workbook.Append(sheets);
           workbook.Append(calculationProperties);
 
           workbookPart.Workbook = workbook;
       }
 
   }
   /// <summary>
   ///
   /// </summary>
   public static class Extensions
   {
       public static string FormatCode(this string sourceString)
       {
           if (sourceString.Contains("<"))
               sourceString = sourceString.Replace("<", "<");
 
           if (sourceString.Contains(">"))
               sourceString = sourceString.Replace(">", ">");
 
           return sourceString;
       }
   }




本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

csharp: Export DataTable to Excel using OpenXml 2.5 in asp.net 的相关文章

  • Java有没有类似微软CHESS的工具?

    是否有类似于 Microsoft 的现有 Java 工具CHESS http research microsoft com chess 或者 CHESS 源代码是否开放 以便我可以尝试将其转换为 Java 谷歌的织线工 http code
  • 如何让 LinqToSql 将“索引提示”传递给 sql server?

    由于我们不能相信我们的客户会更新 sql server 中的索引统计信息等 因此我们过去不得不使用索引提示 http www sql server performance com tips hints general p1 aspx 由于我
  • 如何在 VS2017/2015 中打开 .xproj 文件

    我有一个带有扩展名的 NET core 项目 xproj 当我在VS 2017中打开项目时 项目文件 xproj migrated to csproj 如何打开 xproj 文件 Visual Studio 2017 2015 我需要安装任
  • 如何获取Winforms窗体标题栏高度的大小?

    因此 如果它是工具窗口或可最小化的表单 我希望能够以编程方式获取其高度 这可能吗 如果是这样怎么办 您可以使用以下方法确定工具窗口和普通表单的标题栏高度 Rectangle screenRectangle this RectangleToS
  • 在 .Net 托管的 IronPython 脚本中设置和获取变量

    我正在尝试使用 Net 控制台应用程序中托管的 IronPython 来构建验证规则引擎的原型 我已经将脚本精简到我认为的基础内容 var engine Python CreateEngine engine Execute from Sys
  • 如何正确转义mysql?

    我刚刚发现如果我写 select from tbl where name like foo 然后添加 foo 作为参数及其值 a 用户数据 它不会正确转义 我勒个去 它想要 a 即使我使用参数 我还是忍不住觉得我对 sql 注入持开放态度
  • “你好世界!!”在 .NET 4 中生成 3500 个页面错误

    我正在运行 Windows Vista 和 Visual Studio 2010 使用 NET 4 2 GB RAM 和大约 800 MB 可用空间 我创建了一个 Windows 窗体应用程序 但没有向其中添加任何代码 只需在发布模式下编译
  • 为什么当要求修剪“PRN.NUL”时,TrimStart 会更多地修剪字符?

    这是代码 namespace TrimTest class Program static void Main string args string ToTrim PRN NUL Console WriteLine ToTrim string
  • 如何等待远程 .NET 调试器连接

    今天我遇到了一个问题 我需要远程调试程序 该程序是从另一个系统启动的 所以我真的没有机会在命令行上与它交互 不过我可以很容易地改变它的来源 我需要做的是让程序正常启动 然后等待我用调试器附加到它 我想不出一个让我快乐的方法 我确实发现了这个
  • C# xml序列化必填字段

    我需要将一些字段标记为需要写入 XML 文件 但没有成功 我有一个包含约 30 个属性的配置类 这就是为什么我不能像这样封装所有属性 public string SomeProp get return someProp set if som
  • C# 中的 IPC 机制 - 用法和最佳实践

    不久前我在 Win32 代码中使用了 IPC 临界区 事件和信号量 NET环境下场景如何 是否有任何教程解释所有可用选项以及何时使用以及为什么 微软最近在IPC方面的东西是Windows 通信基础 http en wikipedia org
  • 取消任务

    我尝试运行一个关于取消任务的简单示例 如下所示 CancellationTokenSource tokenSource2 new CancellationTokenSource CancellationToken token2 tokenS
  • 如何根据给定的点生成热图

    我想生成 Windows 形式的热图 我有一组点作为输入 如何以最简单的方式做到这一点 谢谢 基于此处已有的答案 此方法允许您指定Colors您希望用作最大和最小颜色 private Color HeatMapColor double va
  • SQLite .NET 性能,如何加快速度?

    在我的系统上 约 86000 个 SQLite 插入需要长达 20 分钟 意味着每秒约 70 个插入 我要做数百万 我怎样才能加快速度 对每一行的 SQLiteConnection 对象调用 Open 和 Close 会降低性能吗 交易有帮
  • 如何在完成之前从 ReplaySubject 获取最新值

    我需要一种方法来获取添加到 ReplaySubject 中符合特定条件的最新项目 下面的示例代码完成了我需要它做的事情 但感觉不是正确的方法 static void Main string args var o new ReplaySubj
  • 如何有效确保小数值至少有 N 位小数

    我想在进行算术运算之前有效地确保十进制值至少有 N 个位置 在下面的示例中 3 显然我可以格式化 0 000 然后解析 但它的效率相对较低 我正在寻找一种避免与字符串转换的解决方案 我尝试过以下解决方案 decimal d 1 23M d
  • WPF:Prism 对于小型应用程序来说是不是太过分了?

    如果我不将我的应用程序分成不同的模块 否则我会认为 Prism 确实是可行的方法 我应该使用 Prism 吗 我知道 Prism 提供了一个方便的实现ICommand 我可以自己在一页代码中完成 并为我们提供IEventAggregator
  • 以编程方式设置 maxRequestLength

    有一个配置值叫做maxRequestLength 在配置文件中 它看起来像这样
  • C# - OutOfMemoryException 在 JSON 文件上保存列表

    我正在尝试保存压力图的流数据 基本上我有一个压力矩阵定义为 double pressureMatrix new double e Data GetLength 0 e Data GetLength 1 基本上 我得到了其中之一pressur
  • 使用.NET技术录制屏幕视频[关闭]

    Closed 这个问题正在寻求书籍 工具 软件库等的推荐 不满足堆栈溢出指南 help closed questions 目前不接受答案 有没有一种方法可以使用 NET 技术来录制屏幕 无论是桌面还是窗口 我的目标是免费的 我喜欢小型 低

随机推荐