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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
//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
  //https://openxmlsdkjs.codeplex.com/
   //引用: 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;
       }
   }

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/// <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));
       }
   }

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/// <summary>
/// windows 10 Microsoft Edge 测试无效。
///塗聚文註
/// </summary>
/// <param name="dt"></param>
/// <param name="Response"></param>
/// <param name="filename"></param>
public static void Convertexcel(DataTable dt, HttpResponse Response, string filename)
{
 
    //win 10 通不过
    Response.Clear();
    Response.Buffer = true;
    Response.ClearContent();
    Response.ClearHeaders();
    Response.ContentEncoding = System.Text.Encoding.UTF8;
    //Response.AppendHeader("content-disposition", "attachment; filename=myfile.xlsx");
 
 
    //Response.AddHeader "Content-Disposition", "Attachment;Filename=myfile.csv"
    
    //Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";        
    //Response.AddHeader("content-disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(filename, System.Text.Encoding.UTF8) + ".xlsx");
 
    //Response.ContentType = "application/ms-excel";  //application/vnd.ms-excel //2003
    //Response.AddHeader("content-disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(filename, System.Text.Encoding.UTF8) + ".xls");//xlsx
    Response.Write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />");
    Response.Charset = "utf-8";
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
     
    //Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";//2007
    System.IO.StringWriter stringWrite = new System.IO.StringWriter();
    //stringWrite.Encoding
    System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite);
    //htmlWrite.Encoding
    System.Web.UI.WebControls.DataGrid dg = new System.Web.UI.WebControls.DataGrid();
    dg.DataSource = dt;
    dg.DataBind();
    dg.RenderControl(htmlWrite);
    string style = @"<!--mce:2-->";
    Response.Write(style);
    Response.Output.Write(stringWrite.ToString());
    //Response.Write(stringWrite.ToString());
    Response.Flush();
    Response.End();
    //HttpContext.Current.ApplicationInstance.CompleteRequest();
 
}

  http://closedxml.codeplex.com/

http://epplus.codeplex.com/

https://sourceforge.net/projects/closedxmlexcel/

https://github.com/vbjay/ClosedXML

http://stackoverflow.com/questions/23102010/open-xml-reading-from-excel-file

https://openxmlexporttoexcel.codeplex.com/

https://excelpackage.codeplex.com/

https://github.com/OfficeDev/Open-Xml-Sdk

https://openxmlpackaging.codeplex.com/

http://powertools.codeplex.com/

https://github.com/OfficeDev/Open-Xml-PowerTools

http://html2openxml.codeplex.com/

https://github.com/gSerP1983/OpenXml.Excel.Data

https://npoi.codeplex.com/

https://github.com/tonyqus/npoi

 

posted @   ®Geovin Du Dream Park™  阅读(528)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
历史上的今天:
2012-08-02 csharp Remove Empty rows in datatable
2012-08-02 csharp read excel file get sheetName list
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示