C# Convert *.xlsx to Json object

Required dlls:

  • Microsoft.Office.Interop.Excel.dll: you can add reference from reference extension(with office installed), find version 15.0(as Office 2010 or higher), and copy to your project lib to make a fix version.
  • Newtonsoft.Json.dll

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.

/// 
/// Imports *.xlsx file and convert all data to json T type list based on first row as column name.
/// 
public static List ConvertXlsxToJsonObject(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();
            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).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();
}

你可能感兴趣的:(C# Convert *.xlsx to Json object)