C# & WPF

C# Convert *.xlsx to Json object

2018-06-06  本文已影响0人  Kreiven

Required dlls:

T type:

T type is an object you want to convert to, the object should have properties related to first row(case sensitive) in xlsx file.

/// <summary>
/// Imports *.xlsx file and convert all data to json T type list based on first row as column name.
/// </summary>
public static List<T> ConvertXlsxToJsonObject<T>(string filePath)
{

    //Microsoft.Office.Interop.Excel.dll required(test version : 15.0)
    var app = new ApplicationClass();
    Workbook book = null;
    Range range = null;

    try
    {
        app.Visible = false;
        app.ScreenUpdating = false;
        app.DisplayAlerts = false;

        book = app.Workbooks.Open(filePath);
        foreach (Worksheet sheet in book.Worksheets)
        {
            // get a range to work with
            range = sheet.Range["A1"];
            // get the end of values to the right (will stop at the first empty cell)
            range = range.End[XlDirection.xlToRight];
            // get the end of values toward the bottom, looking in the last column (will stop at first empty cell)
            range = range.End[XlDirection.xlDown];

            // get the address of the bottom, right cell
            string downAddress = range.Address[false, false];

            //validate address, first is a-z, second is a number
            int t;
            if (!int.TryParse(downAddress.Substring(1), out t))
            {
                throw new Exception(string.Format("Invalid file: xlsx bottom right cell address: {0}", downAddress));
            }

            // Get the range, then values from a1
            range = sheet.Range["A1", downAddress];
            object[,] values = (object[,])range.Value2;

            var rowCount = values.GetLength(0);
            var colCount = values.GetLength(1);

            var sb = new StringBuilder();
            var strObjList = new List<string>();
            for (int i = 2; i <= rowCount; i++)
            {
                sb.Append("{");
                for (int j = 1; j <= colCount; j++)
                {
                    var key = values[1, j]?.ToString();
                    if (string.IsNullOrWhiteSpace(key))
                    {
                        throw new Exception(string.Format("Column {0} doesn't have a column name.", j));
                    }

                    var value = values[i, j]?.ToString();
                    if (string.IsNullOrWhiteSpace(value))
                    {
                        value = string.Empty;
                    }

                    sb.Append("'").Append(key).Append("'")
                        .Append(":")
                        .Append("'").Append(value).Append("'");
                    if (j != colCount) sb.Append(",");
                }
                sb.Append("}");
                strObjList.Add(sb.ToString());
                sb.Clear();
            }

            //Newtonsoft.Json.dll required
            return strObjList.Select(JsonConvert.DeserializeObject<T>).ToList();
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine("Import excel failed: {0}", ex.Message);
    }
    finally
    {
        range = null;
        book?.Close(false);
        book = null;
        app.Quit();
        app = null;
    }
    return new List<T>();
}
上一篇下一篇

猜你喜欢

热点阅读