openxml讀取xlsx內容

 

            var doc = new ExcelUntil().Open(filename, false);
            var shtContentDict = doc.GetSheetsContent();

            int count = 0;
            foreach (var item in shtContentDict)
                codes.AddRange(GetTextOutput(item.Value, item.Key, count++));

            AkResponse.Write(response, "<" + "script" + ">" + AkCommon.ListJoin(codes, "\r\n") + "</" + "script" + ">");

            doc.Close();
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml;
using System.IO;
using System.Text.RegularExpressions;

namespace Appkit.Data
{
    public class ExcelUntil
    {
        #region 屬性

        /// <summary>
        /// Excel文檔
        /// </summary>
        public SpreadsheetDocument spreadsheetDocument { get; set; }

        /// <summary>
        /// 工作簿
        /// </summary>
        public WorkbookPart workbookPart { get; set; } 

        /// <summary>
        /// Sheet集合
        /// </summary>
        public Sheets sheets { get; set; } 
        #endregion

        public SpreadsheetDocument Open(string filename, bool isEdit)
        {
            spreadsheetDocument = SpreadsheetDocument.Open(filename, isEdit);
            return spreadsheetDocument;
        }

        public SpreadsheetDocument Open(Stream stream, bool isEdit)
        {
            spreadsheetDocument = SpreadsheetDocument.Open(stream, isEdit);
            return spreadsheetDocument;
        }

        public void Close()
        {
            if (null != spreadsheetDocument)
            {
                spreadsheetDocument.Close();
            }
        }

    }

    public static class ExtenOpenXml
    {
        #region base

        public static string[] GetAllSheetnames(this SpreadsheetDocument document)
        {
            List<string> sheetNames = new List<string>();
            var sheets = document.WorkbookPart.Workbook.Descendants<Sheet>();
            foreach (var item in sheets)
            {
                sheetNames.Add(item.Name);
            }
            return sheetNames.ToArray();
        }

        /// <summary>
        /// 獲取worksheet
        /// </summary>
        /// <param name="document"></param>
        /// <param name="sheetName"></param>
        /// <returns></returns>
        public static Worksheet GetWorksheet(this SpreadsheetDocument document, string sheetName = null)
        {
            var sheets = document.WorkbookPart.Workbook.Descendants<Sheet>();
            var sheet = (null == sheetName
                            ? sheets.FirstOrDefault()
                            : sheets.FirstOrDefault(s => s.Name == sheetName)) ?? sheets.FirstOrDefault();
            var worksheetPart = (WorksheetPart)document.WorkbookPart.GetPartById(sheet.Id);
            return worksheetPart.Worksheet;
        }


        public static int GetColMax(this Worksheet worksheet)
        {
            if (string.IsNullOrEmpty(worksheet.SheetDimension.Reference.Value)) return -1;
            string[] ss = worksheet.SheetDimension.Reference.Value.Split(':');
            if (ss.Length == 1) return LetterToInt(GetColumnLetter(ss[0]));
            if (ss.Length != 2) return -1;
            return LetterToInt(GetColumnLetter(ss[1]));

        }

        private static int GetRowNumber(string str)
        {
            return int.Parse(Regex.Replace(str, "[A-Z]", "", RegexOptions.IgnoreCase));
        }

        private static int LetterToInt(string str)
        {
            if (str.Length == 1) return (int)(str[0]) - 65 + 1;
            return ((int)(System.Math.Pow(26, (str.Length - 1)))) * ((int)(str.Substring(0, 1)[0] - 65 + 1)) + LetterToInt(str.Substring(1, str.Length - 1));
        }

        private static int GetRowCount(string dimension)
        {
            if (string.IsNullOrEmpty(dimension)) return -1;
            string[] ss = dimension.Split(':');
            if (ss.Length == 1) return 1;
            if (ss.Length != 2) return -1;
            return GetRowNumber(ss[1]) - GetRowNumber(ss[0]) + 1;
        }

        private static string GetColumnLetter(string str)
        {
            int index = -1; int n = str.Length;
            for (int k = 1; k < n; k++)
            {
                if (str[k] >= '0' && str[k] <= '9')
                {
                    index = k;
                    break;
                }
            }

            if (index > 0)
            {
                return str.Substring(0, index);
            }
            return null;

        }

        /// <summary>
        /// 數字轉字母
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        private static string IntToLetter(int index)
        {
            if (index < 0) { throw new Exception("invalid parameter"); }

            List<string> chars = new List<string>();
            do
            {
                chars.Insert(0, ((char)((index - 1) % 26 + (int)'A')).ToString());
                index = (int)(((index - 1) - (index - 1) % 26) / 26);
            } while (index > 0);

            return String.Join(string.Empty, chars.ToArray());
        }
        /// <summary>
        /// 獲取共享字符串
        /// </summary>
        /// <param name="document"></param>
        /// <returns></returns>
        public static IEnumerable<SharedStringTablePart> GetSharedStringTable(this SpreadsheetDocument document)
        {
            var sharedStringTable = document.WorkbookPart.GetPartsOfType<SharedStringTablePart>();
            return sharedStringTable;
        }

        /// <summary>
        /// 獲取SheetData
        /// </summary>
        /// <param name="document"></param>
        /// <param name="sheetName"></param>
        /// <returns></returns>
        public static SheetData GetFirstSheetData(this SpreadsheetDocument document, string sheetName = null)
        {
            return document.GetWorksheet(sheetName).GetFirstChild<SheetData>();
        }

        /// <summary>
        /// 獲取SheetData
        /// </summary>
        /// <param name="worksheet"></param>
        /// <returns></returns>
        public static SheetData GetFirstSheetData(this Worksheet worksheet)
        {
            return worksheet.GetFirstChild<SheetData>();
        }

        /// <summary>
        /// 獲取Workbook
        /// </summary>
        /// <param name="workbookPart"></param>
        /// <returns></returns>
        public static Workbook GetWorkbook(this WorkbookPart workbookPart)
        {
            return workbookPart.Workbook;
        }

        public static void UpdateCellText(this SheetData sheetData, string cellName, string cellText)
        {
            var cell = sheetData.GetCell(cellName);
            if (null == cell)
                return;
            cell.UpdateCellText(cellText);
        }

        /// <summary>
        /// 修改單元格文本
        /// </summary>
        /// <param name="cell"></param>
        /// <param name="cellText"></param>
        private static void UpdateCellText(this Cell cell, object cellText)
        {
            cell.DataType = GetCellDataType(cellText);
            cell.CellValue = cell.CellValue ?? new CellValue();
            cell.CellValue.Text = cellText.ToString();
        }
        private static CellValues GetCellDataType(object cellText)
        {
            var type = cellText.GetType();
            switch (type.Name)
            {
                case "Int32":
                case "Decimal":
                case "Double":
                case "Int64":
                    return CellValues.Number;
                case "String":
                    return CellValues.String;
                case "DateTime":
                    return CellValues.Date;
                default:
                    return CellValues.String;
            }
        }

        /// <summary>
        /// 修改單元格內容(文本、樣式)
        /// </summary>
        /// <param name="cell"></param>
        /// <param name="cellText"></param>
        /// <param name="cellStyleIndex"></param>
        private static void UpdateCell(this Cell cell, object cellText, uint cellStyleIndex)
        {
            cell.UpdateCellText(cellText);
            cell.StyleIndex = cellStyleIndex;
        }

        /// <summary>
        /// 根據單元格獲取行索引
        /// </summary>
        /// <param name="cellName"></param>
        /// <returns></returns>
        private static uint GetRowIndex(string cellName)
        {
            var regex = new Regex(@"\d+");
            var match = regex.Match(cellName);
            return uint.Parse(match.Value);
        }

        /// <summary>
        /// 獲取行
        /// </summary>
        /// <param name="sheetData"></param>
        /// <param name="rowIndex"></param>
        /// <returns></returns>
        private static Row GetRow(this SheetData sheetData, long rowIndex)
        {
            return sheetData.Elements<Row>().FirstOrDefault(r => r.RowIndex == rowIndex);
        }

        public static IEnumerable<Row> GetAllRow(this Worksheet worksheet)
        {
            return worksheet.GetFirstSheetData().Elements<Row>();

        }


        public static Dictionary<string, string> GetSheetsContent(this SpreadsheetDocument doc) {
            Dictionary<string, string> dict = new Dictionary<string, string>();

            string[] sheetNames = doc.GetAllSheetnames();


            foreach (var sheetName in sheetNames)
            {
                var sheet = doc.GetWorksheet(sheetName);

                int colMin = 1;
                int colMax = sheet.GetColMax();

                List<string> list = new List<string>();
                foreach (var row in sheet.GetAllRow())
                    list.Add(doc.GetRowText(row, colMin, colMax));

                if (0 != list.Count)
                    dict.Add(sheetName,string.Join("\n", list));
            }

            return dict;

        }


        public static string GetRowText(this SpreadsheetDocument doc, Row row, int colMin, int colMax)
        {
            if (colMin < 0 || colMax < 0)
            {
                throw new Exception("列序號不能小於0");
            }
            Dictionary<int, string> rowValues = new Dictionary<int, string>();
            var cells = row.Elements<Cell>();
            foreach (var cell in cells)
            {
                int colNum = LetterToInt(GetColumnLetter(cell.CellReference));
                string txt = GetCellValue(cell, doc.GetSharedStringTable().FirstOrDefault());
                rowValues.Add(colNum, txt);
            }

            List<string> list = new List<string>();
            for (int i = colMin; i <= colMax; i++)
            {
                if (rowValues.ContainsKey(i))
                    list.Add(rowValues[i]);
                else
                    list.Add(null);
            }

            return string.Join("\t", list);
        }


        /// <summary>
        /// 獲取單元格
        /// </summary>
        /// <param name="row"></param>
        /// <param name="cellName"></param>
        /// <returns></returns>
        private static Cell GetCell(this Row row, string cellName)
        {
            return row.Descendants<Cell>().FirstOrDefault(c => c.CellReference.Value == cellName);
        }

        private static Cell GetCell(this SheetData sheetData, string cellName)
        {
            return sheetData.Descendants<Cell>().FirstOrDefault(c => c.CellReference.Value == cellName);
        }

        /// <summary>
        /// 區域名稱集合
        /// </summary>
        /// <param name="workbook"></param>
        /// <returns></returns>
        public static DefinedNames GetDefinedNames(this Workbook workbook)
        {
            return workbook.DefinedNames;
        }


        /// <summary>
        /// 獲取單元格的值
        /// </summary>
        /// <param name="row"></param>
        /// <param name="columnCode"></param>
        /// <param name="sharedStringTablePart"></param>
        /// <returns></returns>

        public static string GetCellValue(this Row row, string columnCode, SharedStringTablePart sharedStringTablePart)
        {
            string value = string.Empty;
            try
            {
                Cell cell = row.GetCell(columnCode);
                if (null != cell)
                    value = GetCellValue(cell, sharedStringTablePart);
                value = string.IsNullOrEmpty(value) ? "" : value;
            }
            catch (Exception)
            {

                throw;
            }
            return value;
        }

        public static string GetCellValue(this Cell cell, SharedStringTablePart sharedStringTablePart)
        {
            if (null == cell)
                return string.Empty;

            if (0 == cell.ChildElements.Count)
                return string.Empty;

            var value = cell.CellValue.InnerText;
            if (null == cell.DataType)
                return value;

            switch (cell.DataType.Value)
            {
                case CellValues.Boolean:
                    value = "0" == value ? "FALSE" : "TRUE";
                    break;
                case CellValues.Number:
                    break;
                case CellValues.Error:
                    break;
                case CellValues.SharedString:
                    if (null != sharedStringTablePart)
                        value = sharedStringTablePart.SharedStringTable.ElementAt(int.Parse(value)).InnerText;
                    break;
                case CellValues.String:
                    break;
                case CellValues.InlineString:
                    break;
                case CellValues.Date:
                    break;
                default:
                    break;
            }

            return value;
        }


        #endregion

    }
}

參考了:https://www.cnblogs.com/kingline/p/9356209.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章