demo:https://files.cnblogs.com/files/guxingy/Excel%E8%BD%AC%E6%8D%A2%E4%B8%BAJson%E5%AF%B9%E8%B1%A1.rar
不太会用博客
待转换的Excel格式
转换后的JSON格式:
Excel转换类:
public class OperationExcel { /// <summary> /// Excel 转换为 Datatable /// </summary> /// <param name="sheetNum">工作表索引</param> /// <param name="isFirstRowColumn">首行为列</param> /// <param name="fileName">Excel文件路径</param> /// <returns></returns> public DataTable ExcelToDataTable(int sheetNum, bool isFirstRowColumn, string fileName) { IWorkbook workbook = null; ISheet sheet = null; DataTable myTable = new DataTable(); try { var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read); if (fileName.IndexOf(".xlsx") > 0) workbook = new XSSFWorkbook(fs); else if (fileName.IndexOf(".xls") > 0) workbook = new HSSFWorkbook(fs); sheet = workbook.GetSheetAt(sheetNum); //工作表不能为空 if (sheet == null) { string str = ""; for (int i = 0; i < workbook.NumberOfSheets; i++) { str += workbook.GetSheetAt(i).SheetName + ","; } str = workbook.NumberOfSheets + str; throw new Exception($"sheet不能为空!参数:{sheetNum} 工作簿信息:{str}"); } //Excel最大列数 int MaxColumnNum = 0; for (int i = 0; i < sheet.LastRowNum; i++) { var row = sheet.GetRow(i); if (row.LastCellNum > MaxColumnNum) { MaxColumnNum = row.LastCellNum; } } //Excel行数 int MaxRowNum = sheet.LastRowNum; //table新增列 for (int i = 0; i < MaxColumnNum; ++i) { //首行为列 if (isFirstRowColumn) { bool addEmptyCell = true;//是否添加空列 ICell cell = sheet.GetRow(0).GetCell(i); if (cell != null) { //table列赋值 string cellValue = "";//列名 if (cell.CellType == CellType.Numeric) { cellValue = cell.NumericCellValue.ToString(); } else { cellValue = cell.StringCellValue; } if (!string.IsNullOrWhiteSpace(cellValue)) { //列数据为Excel的数据 addEmptyCell = false; myTable.Columns.Add(new DataColumn(cellValue)); } } if (addEmptyCell) { myTable.Columns.Add(new DataColumn(""));//列数据为空 } } else { myTable.Columns.Add(new DataColumn(i + "")); } } //起始行 int startRow = 0; if (isFirstRowColumn) { startRow = 1; } //DataTable赋值 for (int i = startRow; i <= MaxRowNum; ++i) { IRow row = sheet.GetRow(i); if (row == null) continue; DataRow NewRow = myTable.NewRow(); for (int j = row.FirstCellNum; j < row.LastCellNum; ++j) { ICell cell = row.GetCell(j); string value = ""; if (cell != null) { //table行赋值 if (cell.CellType == CellType.Numeric) { value = cell.NumericCellValue.ToString(); if ((j == 0) && ((i == 6) || (i == 12))) { //特殊的几个单元格 转换为 日期格式 value = ToDateTimeValue(cell.NumericCellValue.ToString()); } } else { //row.GetCell(j).SetCellType(CellType.String); value = cell.StringCellValue; } } NewRow[j] = value; } myTable.Rows.Add(NewRow); } return myTable; } catch (Exception ex) { throw ex; } } /// <summary> /// DataTable 转换为 Html /// </summary> /// <param name="dt"></param> /// <returns></returns> public string GetHtmlString(DataTable dt) { StringBuilder sb = new StringBuilder(); sb.Append("<html><head>"); sb.Append("<title>Excel转换为Table</title>"); sb.Append("<meta http-equiv='content-type' content='text/html; charset=GB2312'> "); sb.Append("<style type=text/css>"); sb.Append("td{font-size: 9pt;border:solid 1 #000000;}"); sb.Append("table{padding:3 0 3 0;border:solid 1 #000000;margin:0 0 0 0;BORDER-COLLAPSE: collapse;}"); sb.Append("</style>"); sb.Append("</head>"); sb.Append("<body>"); sb.Append("<table cellSpacing='0' cellPadding='0' width ='100%' border='1'>"); sb.Append("<tr valign='middle'>"); sb.Append("<td><b></b></td>"); foreach (DataColumn column in dt.Columns) { sb.Append("<td><b><span>" + column.ColumnName + "</span></b></td>"); } sb.Append("</tr>"); int iColsCount = dt.Columns.Count; int rowsCount = dt.Rows.Count - 1; for (int j = 0; j <= rowsCount; j++) { sb.Append("<tr>"); sb.Append("<td>" + ((int)(j + 1)).ToString() + "</td>"); for (int k = 0; k <= iColsCount - 1; k++) { sb.Append("<td>"); object obj = dt.Rows[j][k]; if (obj == DBNull.Value) { obj = " ";//如果是NULL则在HTML里面使用一个空格替换之 } if (obj.ToString() == "") { obj = " "; } string strCellContent = obj.ToString().Trim(); sb.Append("<span>" + strCellContent + "</span>"); sb.Append("</td>"); } sb.Append("</tr>"); } sb.Append("</table>"); //点击单元格 输出 行和列 sb.Append("<script src='https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js'></script>"); sb.Append("<script type='text/javascript'>"); sb.Append("$('table tbody').on('click', 'td', function (e) {"); sb.Append("var row = $(this).parent().prevAll().length-1 ;"); sb.Append("var column = $(this).prevAll().length-1 ;"); sb.Append("var str = 'dt.Rows[' + row + '][' + column + '].ToString()';"); sb.Append("console.log(str);alert(str);"); sb.Append("});"); sb.Append("</script>"); sb.Append("</body></html>"); return sb.ToString(); } /// <summary> /// 数字格式的时间 转换为 字符串格式的时间 /// 数字格式的时间 如: 42095.7069444444/0.650694444444444 /// </summary> /// <param name="timeStr">数字,如:42095.7069444444/0.650694444444444</param> /// <returns>日期/时间格式</returns> public string ToDateTimeValue(string strNumber) { if (!string.IsNullOrWhiteSpace(strNumber)) { Decimal tempValue; //先检查 是不是数字; if (Decimal.TryParse(strNumber, out tempValue)) { //天数,取整 int day = Convert.ToInt32(Math.Truncate(tempValue)); //这里也不知道为什么. 如果是小于32,则减1,否则减2 //日期从1900-01-01开始累加 // day = day < 32 ? day - 1 : day - 2; DateTime dt = new DateTime(1900, 1, 1).AddDays(day < 32 ? (day - 1) : (day - 2)); //小时:减掉天数,这个数字转换小时:(* 24) Decimal hourTemp = (tempValue - day) * 24;//获取小时数 //取整.小时数 int hour = Convert.ToInt32(Math.Truncate(hourTemp)); //分钟:减掉小时,( * 60) //这里舍入,否则取值会有1分钟误差. Decimal minuteTemp = Math.Round((hourTemp - hour) * 60, 2);//获取分钟数 int minute = Convert.ToInt32(Math.Truncate(minuteTemp)); //秒:减掉分钟,( * 60) //这里舍入,否则取值会有1秒误差. Decimal secondTemp = Math.Round((minuteTemp - minute) * 60, 2);//获取秒数 int second = Convert.ToInt32(Math.Truncate(secondTemp)); //时间格式:00:00:00 string resultTimes = string.Format("{0}:{1}:{2}", (hour < 10 ? ("0" + hour) : hour.ToString()), (minute < 10 ? ("0" + minute) : minute.ToString()), (second < 10 ? ("0" + second) : second.ToString())); if (day > 0) return string.Format("{0} {1}", dt.ToString("yyyy-MM-dd"), resultTimes); else return resultTimes; } } return string.Empty; } }
转换的方法
/// <summary> /// excel 转换为 datatable /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button1_Click(object sender, EventArgs e) { OperationExcel _OperationExcel = new OperationExcel(); DataTable dt = _OperationExcel.ExcelToDataTable(0, true, "21.xls"); } /// <summary> /// datatable 转换为 html /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button2_Click(object sender, EventArgs e) { OperationExcel _OperationExcel = new OperationExcel(); DataTable dt = _OperationExcel.ExcelToDataTable(0, true, "21.xls"); textBox1.Text = _OperationExcel.GetHtmlString(dt); } /// <summary> /// datatable 转换为 json格式 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button3_Click(object sender, EventArgs e) { OperationExcel _OperationExcel = new OperationExcel(); List<ExcelInfo> list = new List<ExcelInfo>(); list.Add(new ExcelInfo("21.xls", 5)); list.Add(new ExcelInfo("22.xls", 5)); list.Add(new ExcelInfo("23.xls", 4)); list.ForEach(c => { for (int i = 0; i < c.SheetCount; i++) { DataTable dt = _OperationExcel.ExcelToDataTable(i, true, c.FileName); string str = CreateStrObj(dt); string num = c.FileName.Replace(".xls", ""); string fileName = $"Y{num}-{i + 1}.txt"; System.IO.File.WriteAllText($"txt//{fileName}", str); } }); MessageBox.Show("格式转换完成!"); } public string CreateStrObj(DataTable dt) { ZLInfo _ZLInfo = new ZLInfo(); //基本信息 _ZLInfo._桥梁名称 = dt.Rows[0][1].ToString(); _ZLInfo._构建类型 = dt.Rows[0][5].ToString(); _ZLInfo._构件编号 = dt.Rows[0][8].ToString(); _ZLInfo._张拉方式 = dt.Rows[0][11].ToString(); _ZLInfo._张拉日期 = ""; _ZLInfo._砼设计强度 = dt.Rows[2][1].ToString(); //详情数据 List<DetailInfor> list = new List<DetailInfor>(); int total = 2; for (int i = 0; i < total; i++) { DetailInfor _DetailInfor = new DetailInfor(); _DetailInfor._孔道号 = dt.Rows[i * 6 + 5][1].ToString(); _DetailInfor._张拉时间 = dt.Rows[5][0].ToString(); _DetailInfor._理论伸长量 = dt.Rows[5][14].ToString(); _DetailInfor._设计张力 = dt.Rows[5][13].ToString(); _DetailInfor._回缩量 = dt.Rows[5][12].ToString(); _DetailInfor._张拉力 = ""; _DetailInfor._油压 = dt.Rows[5][11].ToString(); _DetailInfor._伸长量 = ""; _DetailInfor._伸长量误差 = ""; _DetailInfor._千斤顶编号1 = dt.Rows[5][3].ToString(); _DetailInfor._初始油压1 = dt.Rows[5][5].ToString(); _DetailInfor._初始张拉力1 = dt.Rows[6][5].ToString(); _DetailInfor._初始伸长量1 = dt.Rows[7][5].ToString(); _DetailInfor._2倍初始油压1 = dt.Rows[5][6].ToString(); _DetailInfor._2倍初始张拉力1 = dt.Rows[6][6].ToString(); _DetailInfor._2倍初始伸长量1 = dt.Rows[7][6].ToString(); _DetailInfor._100油压1 = dt.Rows[5][8].ToString(); _DetailInfor._100张拉力1 = dt.Rows[6][8].ToString(); _DetailInfor._100伸长量1 = dt.Rows[7][8].ToString(); _DetailInfor._千斤顶编号2 = dt.Rows[8][3].ToString(); _DetailInfor._初始油压2 = dt.Rows[8][5].ToString(); _DetailInfor._初始张拉力2 = dt.Rows[9][5].ToString(); _DetailInfor._初始伸长量2 = dt.Rows[10][5].ToString(); _DetailInfor._2倍初始油压2 = dt.Rows[8][6].ToString(); _DetailInfor._2倍初始张拉力2 = dt.Rows[9][6].ToString(); _DetailInfor._2倍初始伸长量2 = dt.Rows[10][6].ToString(); _DetailInfor._100油压2 = dt.Rows[8][8].ToString(); _DetailInfor._100张拉力2 = dt.Rows[9][8].ToString(); _DetailInfor._100伸长量2 = dt.Rows[10][8].ToString(); _DetailInfor._是否合格 = ""; list.Add(_DetailInfor); } _ZLInfo._详情数据 = list; string str = JsonConvert.SerializeObject(_ZLInfo); str = str.Replace("_", ""); str = str.Replace("100油压", "100%油压").Replace("100张拉力", "100%张拉力").Replace("100伸长量", "100%伸长量"); return str; }
相关的类
public class ExcelInfo { public string FileName { get; set; } public int SheetCount { get; set; } public ExcelInfo(string FileName, int SheetCount) { this.FileName = FileName; this.SheetCount = SheetCount; } }
public class ZLInfo { public string _桥梁名称 { get; set; } public string _构建类型 { get; set; } public string _构件编号 { get; set; } public string _张拉方式 { get; set; } public string _张拉日期 { get; set; } public string _砼设计强度 { get; set; } public List<DetailInfor> _详情数据 { get; set; } }
public class DetailInfor { public string _孔道号 { get; set; } public string _张拉时间 { get; set; } public string _理论伸长量 { get; set; } public string _设计张力 { get; set; } public string _回缩量 { get; set; } public string _张拉力 { get; set; } public string _油压 { get; set; } public string _伸长量 { get; set; } public string _伸长量误差 { get; set; } public string _千斤顶编号1 { get; set; } public string _初始油压1 { get; set; } public string _初始张拉力1 { get; set; } public string _初始伸长量1 { get; set; } public string _2倍初始油压1 { get; set; } public string _2倍初始张拉力1 { get; set; } public string _2倍初始伸长量1 { get; set; } public string _100油压1 { get; set; } public string _100张拉力1 { get; set; } public string _100伸长量1 { get; set; } public string _千斤顶编号2 { get; set; } public string _初始油压2 { get; set; } public string _初始张拉力2 { get; set; } public string _初始伸长量2 { get; set; } public string _2倍初始油压2 { get; set; } public string _2倍初始张拉力2 { get; set; } public string _2倍初始伸长量2 { get; set; } public string _100油压2 { get; set; } public string _100张拉力2 { get; set; } public string _100伸长量2 { get; set; } public string _是否合格 { get; set; } }