Csharp: read excel file using Open XML SDK 2.5

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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using DocumentFormat.OpenXml.Spreadsheet;
 
 
namespace OpenXmlOficeDemo
{
 
    /// <summary>
    /// Open XML SDK 2.0 for Microsoft Office http://www.microsoft.com/en-us/download/details.aspx?id=5124
    /// Open XML SDK 2.5 for Microsoft Office http://www.microsoft.com/en-us/download/details.aspx?id=30425
    /// Open XML SDK open source  https://github.com/officedev/open-xml-sdk
    /// Open XML SDK 2.5 类库参考 https://msdn.microsoft.com/ZH-CN/library/gg278315.aspx
    /// http://openxmldeveloper.org/
    /// https://github.com/OfficeDev/Open-Xml-PowerTools
    /// https://msdn.microsoft.com/en-us/library/office/bb448854.aspx
    /// https://github.com/OfficeDev <br>    ///https://msdn.microsoft.com/en-us/library/dd452407(v=office.12).aspxhttps://msdn.microsoft.com/en-us/library/dd452407(v=office.12).aspx  
    /// </summary>
    public partial class Form1 : Form
    {
 
        /// <summary>
        ///
        /// </summary>
        public Form1()
        {
            InitializeComponent();
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_Load(object sender, EventArgs e)
        {
 
           
 
 
        }
        /// <summary>
        ///
        /// </summary>
        public class Package
        {
            public string Company { get; set; }
            public double Weight { get; set; }
            public long TrackingNumber { get; set; }
            public DateTime DateOrder { get; set; }
            public bool HasCompleted { get; set; }
        }
        /// <summary>
        /// 生成EXCEL文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            string timeMark = DateTime.Now.ToString("yyyyMMddHHmmss");
            string excelPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "geovindu" + timeMark + ".xlsx");
            List<Package> packages =
                 new List<Package>
                        { new Package { Company = "Coho Vineyard", Weight = 25.2, TrackingNumber = 89453312L, DateOrder = DateTime.Today, HasCompleted = false },
                          new Package { Company = "Lucerne Publishing", Weight = 18.7, TrackingNumber = 89112755L, DateOrder = DateTime.Today, HasCompleted = false },
                          new Package { Company = "Wingtip Toys", Weight = 6.0, TrackingNumber = 299456122L, DateOrder = DateTime.Today, HasCompleted = false },
                          new Package { Company = "Adventure Works", Weight = 33.8, TrackingNumber = 4665518773L, DateOrder =  DateTime.Today.AddDays(-4), HasCompleted = true },
                          new Package { Company = "Test Works", Weight = 35.8, TrackingNumber = 4665518774L, DateOrder =  DateTime.Today.AddDays(-2), HasCompleted = true },
                          new Package { Company = "Good Works", Weight = 48.8, TrackingNumber = 4665518775L, DateOrder =  DateTime.Today.AddDays(-1), HasCompleted = true },
 
                        };
 
            List<string> headerNames = new List<string> { "Company", "Weight", "Tracking Number", "Date Order", "Completed" };
            ExcelFacade excelFacade = new ExcelFacade();
            excelFacade.Create<Package>(excelPath, packages, "Packages", headerNames);
        }
 
        /// <summary>
        /// 读取工作表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
 
            string file = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Sample.xlsx");
            List<SheetNameInfo> sheets = new List<SheetNameInfo>();
            sheets = GetSheetsDu(file);
            this.comboBox1.DataSource = sheets;
            comboBox1.DisplayMember = "SheetName";
            comboBox1.ValueMember = "SheetID";
            //1
            //OpenXmlOficeDemo.SLExcelUtility.SLExcelReader read = new SLExcelUtility.SLExcelReader();
            //var data = (new OpenXmlOficeDemo.SLExcelUtility.SLExcelReader()).ReadExcel(file);
            //this.dataGridView1.DataSource = data.DataRows;
            //2
            //FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read);
            //DataTable dt = ReadAsDataTable(file);
            //this.dataGridView1.DataSource = dt;
           // fs.Close();
           // fs.Dispose();
 
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            string file = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Sample.xlsx");
            //FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read);
            DataTable dt = ReadAsDataTable(file);// ReadExcel(this.comboBox1.SelectedText, fs);
            this.dataGridView1.DataSource = dt;
            //fs.Close();
            //fs.Dispose();
        }
 
        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {
 
            DataSet ds = new DataSet();
            string filePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Sample.xlsx");
            SpreadsheetDocument document = SpreadsheetDocument.Open(filePath, false);
           // var sheets = document.WorkbookPart.Workbook.Descendants<Sheet>();
            var sheets = document.WorkbookPart.Workbook.Sheets;
            foreach (Sheet sheet in sheets)
            {
                //sheet.Id
                // sheet.Name
                    
               // sheet.SheetId
                foreach (var attr in sheet.GetAttributes())              
                {
                    
                    Console.WriteLine("{0}: {1}", attr.LocalName, attr.Value);//工作表名
                }
            }
            WorkbookPart wbPart = document.WorkbookPart; ;
            //SharedStringTable sharedStringTable = wbPart.GetPartsOfType<SharedStringTablePart>().FirstOrDefault().SharedStringTable;
            // SharedStringTable sharedStringTable = document.WorkbookPart.SharedStringTablePart.SharedStringTable;
            string cellValue = null;
            foreach (WorksheetPart worksheetPart in document.WorkbookPart.WorksheetParts)
            {
                 
                //foreach (Sheet sheet in sheets)
                   
                foreach (SheetData sheetData in worksheetPart.Worksheet.Elements<SheetData>())
                {
                    DataTable dataTable = new DataTable();
                    if (sheetData.HasChildren)
                    {
                        foreach (Row row in sheetData.Elements<Row>())
                        {
 
                            //foreach (Cell cell in row.ElementAt(0))
                            //{
                            //    dataTable.Columns.Add(GetCellValue(document, cell)); //标题
                            //    string tile= GetCellValue(document, cell); //标题
                            //     MessageBox.Show(tile);
                            //}
 
                            foreach (Cell cell in row.Elements<Cell>())
                            {
 
 
                              //string tile= GetCellValue(document, cell); //标题
                             // MessageBox.Show(tile);
                                cellValue = cell.InnerText;
 
                                if (cell.DataType == CellValues.SharedString)
                                {
                                    Console.WriteLine("cell val: " );//+ sharedStringTable.ElementAt(Int32.Parse(cellValue)).InnerText);
                                }
                                else
                                {
                                    Console.WriteLine("cell val: " + cellValue);
                                }
                            }
                        }
                    }
                }
            }
            document.Close();
 
 
 
        }
 
        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button5_Click(object sender, EventArgs e)
        {
            try
            {
                string file = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Sample.xlsx");
                DataTable dt = new DataTable();
                string sheename = this.comboBox1.Text;
                dt = ReadIdDataTable(file, sheename);
                this.dataGridView1.DataSource = dt;
            }
            catch (Exception ex)
            {
                ex.Message.ToString();
            }
 
 
 
        }
        /// <summary>
        /// 读取工作表名
        /// 涂聚文
        /// </summary>
        /// <param name="strFileName"></param>
        /// <returns></returns>
        public static List<SheetNameInfo> GetSheetsDu(String strFileName)
        {
            List<SheetNameInfo> sheetinfo = new List<SheetNameInfo>();
            using (SpreadsheetDocument document = SpreadsheetDocument.Open(strFileName, false))
            {
                 var sheets = document.WorkbookPart.Workbook.Sheets;
                 int k = 0;
                 foreach (Sheet sheet in sheets)
                 {
                     SheetNameInfo sheetNameInfo = new SheetNameInfo();
                     sheetNameInfo.SheetName = sheet.Name;
                     sheetNameInfo.Rid = sheet.Id;
                     sheetNameInfo.SheetID = k;//
                     sheetinfo.Add(sheetNameInfo);
                     k++;
                 }
            }
 
            return sheetinfo;
 
        }
 
        /// <summary>
        /// 读取工作表名
        /// EXCEL 2007版以上
        /// </summary>
        /// <param name="strFileName"></param>
        /// <returns></returns>
        public static List<SheetNameInfo> GetSheets(String strFileName)
        {
            string id = string.Empty;
            //  Fill this collection with a list of all the sheets.
            List<SheetNameInfo> sheets = new List<SheetNameInfo>();
            using (SpreadsheetDocument xlPackage = SpreadsheetDocument.Open(strFileName, false))
            {
 
                WorkbookPart workbook = xlPackage.WorkbookPart;
                Stream workbookstr = workbook.GetStream();
                XmlDocument doc = new XmlDocument();
                doc.Load(workbookstr);
                XmlNamespaceManager nsManager = new XmlNamespaceManager(doc.NameTable);
                nsManager.AddNamespace("default", doc.DocumentElement.NamespaceURI);
                XmlNodeList nodelist = doc.SelectNodes("//default:sheets/default:sheet", nsManager);
                int k = 0;
                foreach (XmlNode node in nodelist)
                {
                    SheetNameInfo sheetNameInfo = new SheetNameInfo();
                    String sheetName = String.Empty;
                    sheetName = node.Attributes["name"].Value;
                   // id = node.Attributes["id"].Value;
                    sheetNameInfo.SheetID = int.Parse(node.Attributes["sheetId"].Value.ToString());
                    sheetNameInfo.Rid = node.Attributes["r:id"].Value;
                    sheetNameInfo.SheetName = sheetName;
                    sheets.Add(sheetNameInfo);
                    k++;
                }
            }
            return sheets;
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="cell"></param>
        /// <param name="stringTablePart"></param>
        /// <returns></returns>
        public static String GetValue(Cell cell, SharedStringTablePart stringTablePart)
        {
 
            if (cell.ChildElements.Count == 0)
                return null;
            //get cell value
            String value = cell.CellValue.InnerText;
            //Look up real value from shared string table
            if ((cell.DataType != null) && (cell.DataType == CellValues.SharedString))
                value = stringTablePart.SharedStringTable
                .ChildElements[Int32.Parse(value)]
                .InnerText;
            return value;
 
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static DataTable ReadAsDataTable(string fileName)
        {
            int numID = 0;
            DataTable dataTable = new DataTable();
            using (SpreadsheetDocument spreadSheetDocument = SpreadsheetDocument.Open(fileName, false))
            {
                WorkbookPart workbookPart = spreadSheetDocument.WorkbookPart;
 
                //spreadSheetDocument.WorkbookPart.Workbook.Sheets;
 
                IEnumerable<Sheet> sheets = spreadSheetDocument.WorkbookPart.Workbook.GetFirstChild<Sheets>().Elements<Sheet>();//第一个工作表
                string relationshipId = sheets.First().Id.Value; //工作表
                numID = sheets.Count();
                WorksheetPart worksheetPart = (WorksheetPart)spreadSheetDocument.WorkbookPart.GetPartById(relationshipId);//第一个工作表 
               
                Worksheet workSheet = worksheetPart.Worksheet;
                SheetData sheetData = workSheet.GetFirstChild<SheetData>();
                IEnumerable<Row> rows = sheetData.Descendants<Row>();
 
                foreach (Cell cell in rows.ElementAt(0))
                {
                    dataTable.Columns.Add(GetCellValue(spreadSheetDocument, cell)); //标题
                }
 
                foreach (Row row in rows)
                {
                    DataRow dataRow = dataTable.NewRow();
                    for (int i = 0; i < row.Descendants<Cell>().Count(); i++)
                    {
                        dataRow[i] = GetCellValue(spreadSheetDocument, row.Descendants<Cell>().ElementAt(i));
                    }
 
                    dataTable.Rows.Add(dataRow);
                }
 
            }
            dataTable.Rows.RemoveAt(0);
            return dataTable;
        }
        /// <summary>
        /// 涂聚文
        /// 20150820
        /// 七夕节
        /// </summary>
        /// <param name="fileName">文件名</param>
        /// <param name="sheetName">工作表名</param>
        /// <returns></returns>
        public static DataTable ReadIdDataTable(string fileName, string sheetName)
        {
             
            DataTable dataTable = new DataTable();
            using (SpreadsheetDocument spreadSheetDocument = SpreadsheetDocument.Open(fileName, false))
            {
                WorkbookPart workbookPart = spreadSheetDocument.WorkbookPart;
 
                //spreadSheetDocument.WorkbookPart.Workbook.Sheets;
                Sheet theSheet = workbookPart.Workbook.Descendants<Sheet>().Where(s => s.Name == sheetName).FirstOrDefault();
 
                //IEnumerable<Sheet> sheets = spreadSheetDocument.WorkbookPart.Workbook.GetFirstChild<Sheets>().Elements<Sheet>();//第一个工作表
                //string relationshipId = theSheet.FirstOrDefault().ExtendedAttributes.ElementAt(0); //工作表
               // numID = sheets.Count();
                WorksheetPart worksheetPart = (WorksheetPart)spreadSheetDocument.WorkbookPart.GetPartById(theSheet.Id);//第一个工作表 
 
                Worksheet workSheet = worksheetPart.Worksheet;
                SheetData sheetData = workSheet.GetFirstChild<SheetData>();
                IEnumerable<Row> rows = sheetData.Descendants<Row>();
 
                foreach (Cell cell in rows.ElementAt(0))
                {
                    dataTable.Columns.Add(GetCellValue(spreadSheetDocument, cell)); //标题
                }
 
                foreach (Row row in rows)
                {
                    DataRow dataRow = dataTable.NewRow();
                    for (int i = 0; i < row.Descendants<Cell>().Count(); i++)
                    {
                        dataRow[i] = GetCellValue(spreadSheetDocument, row.Descendants<Cell>().ElementAt(i));
                    }
 
                    dataTable.Rows.Add(dataRow);
                }
 
            }
            dataTable.Rows.RemoveAt(0);
            return dataTable;
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="document"></param>
        /// <param name="cell"></param>
        /// <returns></returns>
        private static string GetCellValue(SpreadsheetDocument document, Cell cell)
        {
            SharedStringTablePart stringTablePart = document.WorkbookPart.SharedStringTablePart;
            string value = cell.CellValue.InnerXml;
 
            if (cell.DataType != null && cell.DataType.Value == CellValues.SharedString)
            {
                return stringTablePart.SharedStringTable.ChildElements[Int32.Parse(value)].InnerText;
            }
            else
            {
                return value;
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="sheetName"></param>
        /// <param name="addressName"></param>
        /// <returns></returns>
        private static string GetCellValue(string fileName, string sheetName, string addressName)
        {
            string value = null;
 
            using (SpreadsheetDocument document = SpreadsheetDocument.Open(fileName, false))
            {
                WorkbookPart wbPart = document.WorkbookPart;
 
                // Find the sheet with the supplied name, and then use that Sheet
                // object to retrieve a reference to the appropriate worksheet.
                Sheet theSheet = wbPart.Workbook.Descendants<Sheet>().Where(s => s.Name == sheetName).FirstOrDefault();
                if (theSheet == null)
                {
                    throw new ArgumentException("sheetName");
                }
                // Retrieve a reference to the worksheet part, and then use its
                // Worksheet property to get a reference to the cell whose
                // address matches the address you supplied:
                WorksheetPart wsPart = (WorksheetPart)(wbPart.GetPartById(theSheet.Id));
 
                Cell theCell = wsPart.Worksheet.Descendants<Cell>().Where(c => c.CellReference == addressName).FirstOrDefault();
                // If the cell does not exist, return an empty string:
                if (theCell != null)
                {
                    value = theCell.InnerText;
                    // If the cell represents a numeric value, you are done.
                    // For dates, this code returns the serialized value that
                    // represents the date. The code handles strings and Booleans
                    // individually. For shared strings, the code looks up the
                    // corresponding value in the shared string table. For Booleans,
                    // the code converts the value into the words TRUE or FALSE.
                    if (theCell.DataType != null)
                    {
                        switch (theCell.DataType.Value)
                        {
                            case CellValues.SharedString:
                                // For shared strings, look up the value in the shared
                                // strings table.
                                var stringTable = wbPart.
                                  GetPartsOfType<SharedStringTablePart>().FirstOrDefault();
                                // If the shared string table is missing, something is
                                // wrong. Return the index that you found in the cell.
                                // Otherwise, look up the correct text in the table.
                                if (stringTable != null)
                                {
                                    value = stringTable.SharedStringTable.
                                      ElementAt(int.Parse(value)).InnerText;
                                }
                                break;
 
                            case CellValues.Boolean:
                                switch (value)
                                {
                                    case "0":
                                        value = "FALSE";
                                        break;
                                    default:
                                        value = "TRUE";
                                        break;
                                }
                                break;
                        }
                    }
                }
            }
            return value;
        }

  

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
/// <summary>
   ///
   /// </summary>
   public class SheetNameInfo
   {
       private int _sheetId;
       private string _sheetName;
 
       private string _rid;
 
       /// <summary>
       ///
       /// </summary>
       public int SheetID
       {
           get{return _sheetId;}
           set{_sheetId= value;}
       }
       /// <summary>
       ///
       /// </summary>
       public string SheetName
       {
           get { return _sheetName; }
           set { _sheetName = value; }
       }
       /// <summary>
       ///
       /// </summary>
       public string Rid
       {
           get { return _rid; }
           set { _rid = value; }
       }
   }

 

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
internal class ExcelHelper
    {
        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;
                }
            }
 
            public ColumnCaption()
            {
                this.InitCollection();
            }
 
            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();
            }
        }
 
        internal string ExportToExcel(DataTable table)
        {
            string excelfile = Path.GetTempPath() + Guid.NewGuid().ToString() + ".xlsx";
            using (SpreadsheetDocument excelDoc = SpreadsheetDocument.Create(excelfile, DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook))
            {
                CreateExcelParts(excelDoc, table);
            }
            return excelfile;
        }
 
        private void CreateExcelParts(SpreadsheetDocument spreadsheetDoc, DataTable data)
        {
            WorkbookPart workbookPart = spreadsheetDoc.AddWorkbookPart();
            CreateWorkbookPart(workbookPart);
 
            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)
        {
            Workbook workbook = new Workbook();
            Sheets sheets = new Sheets();
 
            Sheet sheet = new Sheet()
            {
                Name = "Book" + 1,
                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;
        }
 
    }
 
    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
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        BindGrid();
    }
    SetChache();
}
 
private void SetChache()
{
    Response.Cache.SetCacheability(HttpCacheability.Public);
    Response.Cache.SetExpires(DateTime.Now.AddYears(1));
}
 
private void BindGrid()
{
    grdvTest.DataSource = new TestData().GetSampleData();
    grdvTest.DataBind();
}
 
protected void btnExport_Click(object sender, EventArgs e)
{
    DataTable table = new DataTable();
    CreateTable(grdvTest, ref table);
 
    string file = new ExcelHelper().ExportToExcel(table);
    string rootPath = HttpContext.Current.Server.MapPath("~").ToString();
    string localCopy = Guid.NewGuid().ToString() + ".xlsx";
    File.Copy(file, rootPath + localCopy);
 
    Response.Redirect(localCopy);
}
 
private void CreateTable(GridView grdvTest, ref DataTable table)
{
    // create columns
    for (int i = 0; i < grdvTest.HeaderRow.Cells.Count; i++)
        table.Columns.Add(grdvTest.HeaderRow.Cells[i].Text);
 
    // fill rows
    foreach (GridViewRow row in grdvTest.Rows)
    {
        DataRow dr;
        dr = table.NewRow();
 
        for (int i = 0; i < row.Cells.Count; i++)
        {
            dr[i] = row.Cells[i].Text.Replace(" ", " ");
        }
        table.Rows.Add(dr);
    }
}

  

 https://openxmlexporttoexcel.codeplex.com/

http://www.codeproject.com/Tips/366446/Export-GridView-Data-to-Excel-using-OpenXml

http://www.codeproject.com/Articles/670141/Read-and-Write-Microsoft-Excel-with-Open-XML-SDK

https://www.microsoft.com/en-us/download/details.aspx?id=17985

posted @   ®Geovin Du Dream Park™  阅读(1037)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
< 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
点击右上角即可分享
微信分享提示