记点笔记,加深印象!最近有个导入Excel工能需要完成,Excel列名是中文的,导入Excel我用的NPOI插件,如果不对Excel做解析,列名有可能会给我带来一些字符方面的麻烦,于是想到了一个比较low的办法,做一个Json配置文件,对应我的Excel列头,然后读取Excel时与json文件匹配,同时需要校验Excel数据是否合法,创建DataTable。主要代码如下:

1.Json文件:

[
{
"Name": "Inventory",
"CnName":"盘点单明细",
"Columns": [
{
"Name": "warehouseCode",
"CnName": "仓库编码",
"Regex": "/^[\\s\\S]*.*[^\\s][\\s\\S]*$/",
"ErrorMsg": "4rwrewrwr"
},
{
"Name": "ownerCode",
"CnName": "货主编码",
"Regex": "",
"ErrorMsg": "4rwrewrwr"
},
{
"Name": "itemCode",
"CnName": "商品编码",
"Regex": "",
"ErrorMsg": "4rwrewrwr"
},
{
"Name": "itemName",
"CnName": "商品名称",
"Regex": "",
"ErrorMsg": "4rwrewrwr"
},
{
"Name": "barCode",
"CnName": "条形码",
"Regex": "",
"ErrorMsg": "4rwrewrwr"
},
{
"Name": "quantity",
"CnName": "系统数量",
"Regex": "",
"ErrorMsg": "4rwrewrwr"
},
{
"Name": "location",
"CnName": "货位",
"Regex": "",
"ErrorMsg": "4rwrewrwr"
},
{
"Name": "expireDate",
"CnName": "过期日期",
"Regex": "",
"ErrorMsg": "4rwrewrwr"
}
]
}
]

2.接受Json文件类:

 public class Sheets
{
public string Name { get; set; }
public string CnName { get; set; }
public List<Column> Columns { get; set; }
} public class Column
{
public string Name { get; set; }
public string CnName { get; set; }
public string Regex { get; set; }
public string ErrorMsg { get; set; }
}

3.具体解析Excel函数

public static DataTable[] ReadExcelToDataTables2(string mapJsonPath, string excelPath,out string msg)
{
msg = "";
List<Sheets> listSheet = new List<Sheets>();
string jsonFile = mapJsonPath;//@"C:\Users\user\source\repos\ConsoleApp1\ConsoleApp1\Map.json";
string json = System.IO.File.ReadAllText(jsonFile, Encoding.Default);
listSheet = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Sheets>>(json);
string excelpath = excelPath; //@"C:\Users\user\Desktop\test.xls";
FileStream fs = null;
DataTable[] tables = null;
int sheetCount = ;
NPOI.HSSF.UserModel.HSSFWorkbook book = null;
NPOI.XSSF.UserModel.XSSFWorkbook workbook = null;
try
{
using (fs = new FileStream(excelpath, FileMode.Open, FileAccess.Read))
{
try
{
book = new NPOI.HSSF.UserModel.HSSFWorkbook(fs);
}
catch (Exception)
{
fs = new FileStream(excelpath, FileMode.Open, FileAccess.Read);
workbook = new XSSFWorkbook(fs);
}
if (book != null)
{
sheetCount = book.NumberOfSheets;
}
else
{
sheetCount = workbook.NumberOfSheets;
}
tables = new DataTable[sheetCount];
DataTable dt = null;
for (int sheetIndex = ; sheetIndex < sheetCount; sheetIndex++)
{
NPOI.SS.UserModel.ISheet sheet = null;
if (book != null)
{
sheet = book.GetSheetAt(sheetIndex);
}
else
{
sheet = workbook.GetSheetAt(sheetIndex);
}
if (sheet == null) continue;
NPOI.SS.UserModel.IRow row = sheet.GetRow();
if (row == null) continue;
int firstCellNum = row.FirstCellNum;
int lastCellNum = row.LastCellNum;
if (firstCellNum == lastCellNum) continue;
string tempSheetName = sheet.SheetName;
string sheetName = listSheet.Find(p => p.CnName == tempSheetName).Name;
dt = new DataTable(sheetName);
for (int i = firstCellNum; i < lastCellNum; i++)
{
string fieldTempName = row.GetCell(i).StringCellValue;
var fieldName = listSheet[sheetIndex].Columns.Find(p => p.CnName == fieldTempName).Name;
dt.Columns.Add(fieldName, typeof(string));
}
for (int i = ; i <= sheet.LastRowNum; i++)
{ DataRow dataRow = dt.Rows.Add(); for (int j = firstCellNum; j < lastCellNum; j++)
{
var cellValue = "";
if (sheet.GetRow(i).GetCell(j) != null)
{
if (sheet.GetRow(i).GetCell(j).CellType == CellType.Numeric && DateUtil.IsCellDateFormatted(sheet.GetRow(i).GetCell(j)))
{
cellValue = sheet.GetRow(i).GetCell(j).DateCellValue.ToString("yyyy/MM/dd");
}
else
{
sheet.GetRow(i).GetCell(j).SetCellType(NPOI.SS.UserModel.CellType.String);
cellValue = sheet.GetRow(i).GetCell(j).StringCellValue;
} }
string errorMsg = listSheet[sheetIndex].Columns[j].ErrorMsg;
if (!string.IsNullOrEmpty(errorMsg))
{
string regex = listSheet[sheetIndex].Columns[j].Regex;
if (!string.IsNullOrEmpty(regex))
{
Match result = Regex.Match(cellValue, regex); //正则校验
if (!result.Success)
{
msg += string.Format("Excel第{0}个sheet的第{1}行,第{2}列,数据错误:{3}\r\n", sheetIndex + , i, j+, errorMsg);
continue;
}
}
}
dataRow[j] = cellValue;
}
}
if (!string.IsNullOrEmpty(msg))
{
return new DataTable[] { };
}
tables[sheetIndex] = dt;
}
}
}
catch (Exception e)
{ throw e;
}
return tables;
}
}

NPOI+Json文件解析Excel的更多相关文章

  1. Golang Json文件解析为结构体工具-json2go

    代码地址如下:http://www.demodashi.com/demo/14946.html 概述 json2go是一个基于Golang开发的轻量json文件解析.转换命令行工具,目前支持转换输出到 ...

  2. PHP JSON文件解析并获取key、value,判断key是否存在

    /****************************************************************************** * PHP JSON文件解析并获取key ...

  3. 【微信】微信小程序 微信开发工具中新创建的json文件,编译报错VM1781:2 pages/module/module.json 文件解析错误 SyntaxError: Unexpected end of JSON input

    如果新创建报错:编译报错VM1781:2 pages/module/module.json 文件解析错误  SyntaxError: Unexpected end of JSON input 解决方法 ...

  4. Json文件解析(下)

    Json文件解析(下) 代码地址:https://github.com/nlohmann/json   从STL容器转换 任何序列容器(std::array,std::vector,std::dequ ...

  5. Json文件解析(上)

    Json文件解析(上) 代码地址:https://github.com/nlohmann/json 自述文件 alt=GitHub赞助商 data-canonical-src="https: ...

  6. Twaver的mono-desiner导出的json文件解析

    以画的交换机为例,其他大概都差不多. 利用Twaver做出交换机模型如图1所示,其中,每一个端口都是一个单独的对象.具体Twaver操作流程参见网址:http://twaver.servasoft.c ...

  7. Python实现读取json文件到excel表

    一.需求 1.'score.json' 文件内容: { "1":["小花",99,100,98.5], "2":["小王" ...

  8. json 文件解析与应用

    第一步:首先弄一个 json 文件   我这里成为 config.json 内容如下 { ": { , "desc":"中华人民共和国" }, &qu ...

  9. Json文件转Excel

    先创建一个web项目,在根目录放置需要转换的json文件,直接读取静态Json文件加载数据进行转换,代码如下: string Json = string.Empty; List<object&g ...

随机推荐

  1. solr查询优化(实践了一下效果比较明显)

    什么是filtercache? solr应用中为了提高查询速度有可以利用几种cache来优化查询速度,分别是fieldValueCache,queryResultCache,documentCache ...

  2. Web前端应该从哪些方面来优化网站

    作者:斯迪链接:https://www.zhihu.com/question/21658448/answer/18903129来源:知乎著作权归作者所有,转载请联系作者获得授权. 不知道是哪位大牛的文 ...

  3. python写exploit采集器

    前言: 根据天文地理与风水学,我掐指一算的看到了一篇不错的文章,文章里面写到整理exploit 我顿时心理想写一个exploit采集器,那么说时迟那时快.就开始写了 代码: 思路:http://exp ...

  4. python中tornado的第一个例子

    1  先安装tornado pip install tornado 2 新建tor.py 记住不能建立 tornado.py 这样的名字  不然会报错 ImportError: No module n ...

  5. zk分布式锁-排它锁简单实现

    package Lock; import java.util.concurrent.CountDownLatch;import java.util.concurrent.TimeUnit;import ...

  6. linux之cut

    [linux之cut] -b:字节 -c:字符 -d:自定义域 -f:域范围 参考:http://wenku.baidu.com/view/9399bc8383d049649b66588b.html

  7. 数论知识总结——史诗大作(这是一个flag)

    1.快速幂 计算a^b的快速算法,例如,3^5,我们把5写成二进制101,3^5=3^1*1+3^2*2+3^4*1 ll fast(ll a,ll b){ll ans=;,a=mul(a,a)))a ...

  8. java多线程启动的方法runnable和callable

  9. [udemy]WebDevelopment_Bootstrap,Templates

    Bootstrap Introduction Bootstrap 相对于CSS, JS 就像PPT模板相对于PPT 说白了就是前人已经做好了(pre-build)很多模板,你可以直接拿来主义 Boot ...

  10. Win10 Cygwin Cd Permission denied

    问题描述 在win10或者win系统上面,使用cygwin的时候, 有时候会出现, 权限问题. 即使是管理员也不行. 问题分析 这个问题,我个人觉得,主要是使用不当造成的. 也就是说, 可能使用chm ...