智云SRM-WEBAPI(目前客户通用API)
yangle
2022-07-06 d0195342b6bb665df9e1437cf2d7c72c1b8d854f
excel 导入
4个文件已修改
2个文件已添加
1688 ■■■■■ 已修改文件
WebAPI/Controllers/NpoiHelper.cs 1339 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
WebAPI/Controllers/POOrderBillExcelController.cs 300 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
WebAPI/Web.config 4 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
WebAPI/WebAPI.csproj 28 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
WebAPI/packages.config 13 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
WindowsFormsApp1/App.config 4 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
WebAPI/Controllers/NpoiHelper.cs
New file
@@ -0,0 +1,1339 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using NPOI.HSSF.UserModel;
using System.Data;
using System.Drawing;
using NPOI.HSSF.Util;
using NPOI.SS.UserModel;
using NPOI.HPSF;
using NPOI.XSSF.UserModel;
namespace WebAPI.Controllers
{
    /// <summary>
    /// Excel文件到DataSet的转换类
    /// </summary>
    public class NpoiHelper
    {
        #region 读取Excel文件内容转换为DataSet
        int ReadExcelEndRow = 0;
        /// <summary>
        /// 读取Excel文件内容转换为DataSet,列名依次为 "c0"……c[columnlength-1]
        /// </summary>
        /// <param name="FileName">文件绝对路径</param>
        /// <param name="startRow">数据开始行数(1为第一行)</param>
        /// <param name="ColumnDataType">每列的数据类型</param>
        /// <param name="numType">获取数据簿的类型</param>
        /// <param name="name">工作簿的名字</param>
        /// <returns></returns>
        public DataSet ReadExcel(string FileName, int startRow,int numType,string name, params NpoiDataType[] ColumnDataType)
        {
            string colNamePix = "F";
            int ertime = 0;
            int intime = 0;
            DataSet ds = new DataSet("ds");
            DataTable dt = new DataTable("dt");
            DataRow dr;
            StringBuilder sb = new StringBuilder();
            using (FileStream stream = new FileStream(@FileName, FileMode.Open, FileAccess.Read))
            {
                IWorkbook workbook = WorkbookFactory.Create(stream);//使用接口,自动识别excel2003/2007格式
                                                                    //for (int k = 0; k < 14; k++)
                ISheet sheet = null ;                                         //{
                if (numType == 1)//numType==1 获取工作簿按照下标
                {
                     sheet = workbook.GetSheetAt(int.Parse(name));//得到里面第一个sheet
                }
                else if (numType == 2)//numType==12 获取工作簿按照 工作簿的名字
                {
                     sheet = workbook.GetSheet(name);//得到里面第一个sheet
                }
                int j;
                IRow row;
                #region ColumnDataType赋值
                if (ColumnDataType.Length <= 0)
                {
                    row = sheet.GetRow(startRow - 1);//得到第i行
                    ColumnDataType = new NpoiDataType[row.LastCellNum];
                    for (int i = 0; i < row.LastCellNum; i++)
                    {
                        ICell hs = row.GetCell(i, MissingCellPolicy.CREATE_NULL_AS_BLANK);
                        ColumnDataType[i] = GetCellDataType(hs); //NpoiDataType.Blank;
                                                                 //if (i == 6)
                                                                 //{
                                                                 //    ColumnDataType[i] = NpoiDataType.Numeric;
                                                                 //}
                    }
                }
                #endregion
                for (j = 0; j < ColumnDataType.Length; j++)
                {
                    Type tp = GetDataTableType(ColumnDataType[j]);
                    //if (j == 6)
                    //{
                    //    tp = typeof(double);
                    //}
                    dt.Columns.Add(colNamePix + (j + 1), tp);
                }
                ReadExcelEndRow = ReadExcelEndRow == 0 ? sheet.PhysicalNumberOfRows : ReadExcelEndRow;
                for (int i = startRow - 1; i <= ReadExcelEndRow; i++)
                {
                    row = sheet.GetRow(i);//得到第i行
                    if (row == null) continue;
                    try
                    {
                        dr = dt.NewRow();
                        for (j = 0; j < ColumnDataType.Length; j++)
                        {
                            dr[colNamePix + (j + 1)] = GetCellData(ColumnDataType[j], row, j);
                        }
                        dt.Rows.Add(dr);
                        intime++;
                    }
                    catch (Exception er)
                    {
                        ertime++;
                        sb.Append(string.Format("第{0}行出错:{1}\r\n", i + 1, er.Message));
                        continue;
                    }
                }
                ds.Tables.Add(dt);
                //}
            }
            if (ds.Tables[0].Rows.Count == 0 && sb.ToString() != "") throw new Exception(sb.ToString());
            return ds;
        }
        #endregion
        #region//读取多个sheet
        public DataSet ReadExcelSub(string FileName, int startRow, params NpoiDataType[] ColumnDataType)
        {
            string colNamePix = "F";
            int ertime = 0;
            int intime = 0;
            DataSet ds = new DataSet("ds");
            DataTable dt0 = new DataTable("dt0");
            DataTable dt1 = new DataTable("dt1");
            DataTable dt2 = new DataTable("dt2");
            DataTable dt3 = new DataTable("dt3");
            DataTable dt4 = new DataTable("dt4");
            DataTable dt5 = new DataTable("dt5");
            DataTable dt6 = new DataTable("dt6");
            DataTable dt7 = new DataTable("dt7");
            DataTable dt8 = new DataTable("dt8");
            DataTable dt9 = new DataTable("dt9");
            DataTable dt10 = new DataTable("dt10");
            DataTable dt11 = new DataTable("dt11");
            DataTable dt12 = new DataTable("dt12");
            DataTable dt13 = new DataTable("dt13");
            DataRow dr;
            StringBuilder sb = new StringBuilder();
            using (FileStream stream = new FileStream(@FileName, FileMode.Open, FileAccess.Read))
            {
                //根据路径通过已存在的excel来创建HSSFWorkbook,即整个excel文档
                HSSFWorkbook workbook = new HSSFWorkbook(stream);
                //XSSFWorkbook workbook = new XSSFWorkbook(stream);
                int x = workbook.NumberOfSheets;
                List<string> sheetNames = new List<string>();
                for (int i = 0; i < x; i++)
                {
                    //sheetNames.Add(workbook.Workbook.GetSheetName(i));
                    ISheet sheet = workbook.GetSheetAt(i);
                    int j;
                    IRow row;
                    #region ColumnDataType赋值
                    if (ColumnDataType.Length <= 0)
                    {
                        row = sheet.GetRow(startRow - 1);//得到第i行
                        ColumnDataType = new NpoiDataType[row.LastCellNum];
                        for (int a = 0; x < row.LastCellNum; a++)
                        {
                            ICell hs = row.GetCell(a, MissingCellPolicy.CREATE_NULL_AS_BLANK);
                            ColumnDataType[a] = GetCellDataType(hs); //NpoiDataType.Blank;
                        }
                    }
                    #endregion
                    for (j = 0; j < ColumnDataType.Length; j++)
                    {
                        Type tp = GetDataTableType(ColumnDataType[j]);//得到每一列的类型
                        ReadExcelEndRow = 0;
                        if (i == 0)
                        {
                            dt0.Columns.Add(colNamePix + (j + 1), tp);
                        }
                        else if (i == 1)
                        {
                            dt1.Columns.Add(colNamePix + (j + 1), tp);
                        }
                        else if (i == 2)
                        {
                            dt2.Columns.Add(colNamePix + (j + 1), tp);
                        }
                        else if (i == 3)
                        {
                            dt3.Columns.Add(colNamePix + (j + 1), tp);
                        }
                        else if (i == 4)
                        {
                            dt4.Columns.Add(colNamePix + (j + 1), tp);
                        }
                        else if (i == 5)
                        {
                            dt5.Columns.Add(colNamePix + (j + 1), tp);
                        }
                        else if (i == 6)
                        {
                            dt6.Columns.Add(colNamePix + (j + 1), tp);
                        }
                        else if (i == 7)
                        {
                            dt7.Columns.Add(colNamePix + (j + 1), tp);
                        }
                        else if (i == 8)
                        {
                            dt8.Columns.Add(colNamePix + (j + 1), tp);
                        }
                        else if (i == 9)
                        {
                            dt9.Columns.Add(colNamePix + (j + 1), tp);
                        }
                        else if (i == 10)
                        {
                            dt10.Columns.Add(colNamePix + (j + 1), tp);
                        }
                        else if (i == 11)
                        {
                            dt11.Columns.Add(colNamePix + (j + 1), tp);
                        }
                        else if (i == 12)
                        {
                            dt12.Columns.Add(colNamePix + (j + 1), tp);
                        }
                        else if (i == 13)
                        {
                            dt13.Columns.Add(colNamePix + (j + 1), tp);
                        }
                    }
                    ReadExcelEndRow = ReadExcelEndRow == 0 ? sheet.PhysicalNumberOfRows : ReadExcelEndRow;
                    for (int a = startRow - 1; a <= ReadExcelEndRow; a++)
                    {
                        row = sheet.GetRow(a);//得到第i行
                        if (row == null) continue;
                        try
                        {
                            if (i == 0)
                            {
                                dr = dt0.NewRow();
                                for (j = 0; j < ColumnDataType.Length; j++)
                                {
                                    dr[colNamePix + (j + 1)] = GetCellData(ColumnDataType[j], row, j);
                                }
                                dt0.Rows.Add(dr);
                                intime++;
                            }
                            else if (i == 1)
                            {
                                dr = dt1.NewRow();
                                for (j = 0; j < ColumnDataType.Length; j++)
                                {
                                    dr[colNamePix + (j + 1)] = GetCellData(ColumnDataType[j], row, j);
                                }
                                dt1.Rows.Add(dr);
                                intime++;
                            }
                            else if (i == 2)
                            {
                                dr = dt2.NewRow();
                                for (j = 0; j < ColumnDataType.Length; j++)
                                {
                                    dr[colNamePix + (j + 1)] = GetCellData(ColumnDataType[j], row, j);
                                }
                                dt2.Rows.Add(dr);
                                intime++;
                            }
                            else if (i == 3)
                            {
                                dr = dt3.NewRow();
                                for (j = 0; j < ColumnDataType.Length; j++)
                                {
                                    dr[colNamePix + (j + 1)] = GetCellData(ColumnDataType[j], row, j);
                                }
                                dt3.Rows.Add(dr);
                                intime++;
                            }
                            else if (i == 4)
                            {
                                dr = dt4.NewRow();
                                for (j = 0; j < ColumnDataType.Length; j++)
                                {
                                    dr[colNamePix + (j + 1)] = GetCellData(ColumnDataType[j], row, j);
                                }
                                dt4.Rows.Add(dr);
                                intime++;
                            }
                            else if (i == 5)
                            {
                                dr = dt5.NewRow();
                                for (j = 0; j < ColumnDataType.Length; j++)
                                {
                                    dr[colNamePix + (j + 1)] = GetCellData(ColumnDataType[j], row, j);
                                }
                                dt5.Rows.Add(dr);
                                intime++;
                            }
                            else if (i == 6)
                            {
                                dr = dt6.NewRow();
                                for (j = 0; j < ColumnDataType.Length; j++)
                                {
                                    dr[colNamePix + (j + 1)] = GetCellData(ColumnDataType[j], row, j);
                                }
                                dt6.Rows.Add(dr);
                                intime++;
                            }
                            else if (i == 7)
                            {
                                dr = dt7.NewRow();
                                for (j = 0; j < ColumnDataType.Length; j++)
                                {
                                    dr[colNamePix + (j + 1)] = GetCellData(ColumnDataType[j], row, j);
                                }
                                dt7.Rows.Add(dr);
                                intime++;
                            }
                            else if (i == 8)
                            {
                                dr = dt8.NewRow();
                                for (j = 0; j < ColumnDataType.Length; j++)
                                {
                                    dr[colNamePix + (j + 1)] = GetCellData(ColumnDataType[j], row, j);
                                }
                                dt8.Rows.Add(dr);
                                intime++;
                            }
                            else if (i == 9)
                            {
                                dr = dt9.NewRow();
                                for (j = 0; j < ColumnDataType.Length; j++)
                                {
                                    dr[colNamePix + (j + 1)] = GetCellData(ColumnDataType[j], row, j);
                                }
                                dt9.Rows.Add(dr);
                                intime++;
                            }
                            else if (i == 10)
                            {
                                dr = dt10.NewRow();
                                for (j = 0; j < ColumnDataType.Length; j++)
                                {
                                    dr[colNamePix + (j + 1)] = GetCellData(ColumnDataType[j], row, j);
                                }
                                dt10.Rows.Add(dr);
                                intime++;
                            }
                            else if (i == 11)
                            {
                                dr = dt11.NewRow();
                                for (j = 0; j < ColumnDataType.Length; j++)
                                {
                                    dr[colNamePix + (j + 1)] = GetCellData(ColumnDataType[j], row, j);
                                }
                                dt11.Rows.Add(dr);
                                intime++;
                            }
                            else if (i == 12)
                            {
                                dr = dt12.NewRow();
                                for (j = 0; j < ColumnDataType.Length; j++)
                                {
                                    dr[colNamePix + (j + 1)] = GetCellData(ColumnDataType[j], row, j);
                                }
                                dt12.Rows.Add(dr);
                                intime++;
                            }
                            else if (i == 13)
                            {
                                dr = dt13.NewRow();
                                for (j = 0; j < ColumnDataType.Length; j++)
                                {
                                    dr[colNamePix + (j + 1)] = GetCellData(ColumnDataType[j], row, j);
                                }
                                dt13.Rows.Add(dr);
                                intime++;
                            }
                        }
                        catch (Exception er)
                        {
                            ertime++;
                            sb.Append(string.Format("第{0}行出错:{1}\r\n", i + 1, er.Message));
                            continue;
                        }
                    }
                    if (i == 0)
                    {
                        ds.Tables.Add(dt0);
                    }
                    else if (i == 1)
                    {
                        ds.Tables.Add(dt1);
                    }
                    else if (i == 2)
                    {
                        ds.Tables.Add(dt2);
                    }
                    else if (i == 3)
                    {
                        ds.Tables.Add(dt3);
                    }
                    else if (i == 4)
                    {
                        ds.Tables.Add(dt4);
                    }
                    else if (i == 5)
                    {
                        ds.Tables.Add(dt5);
                    }
                    else if (i == 6)
                    {
                        ds.Tables.Add(dt6);
                    }
                    else if (i == 7)
                    {
                        ds.Tables.Add(dt7);
                    }
                    else if (i == 8)
                    {
                        ds.Tables.Add(dt8);
                    }
                    else if (i == 9)
                    {
                        ds.Tables.Add(dt9);
                    }
                    else if (i == 10)
                    {
                        ds.Tables.Add(dt10);
                    }
                    else if (i == 11)
                    {
                        ds.Tables.Add(dt11);
                    }
                    else if (i == 12)
                    {
                        ds.Tables.Add(dt12);
                    }
                    else if (i == 13)
                    {
                        ds.Tables.Add(dt13);
                    }
                }
                //IWorkbook workbook = WorkbookFactory.Create(stream);//使用接口,自动识别excel2003/2007格式
                //ISheet sheet = workbook.GetSheetAt(0);//得到里面第一个sheet
            }
            //if (ds.Tables[0].Rows.Count == 0 && sb.ToString() != "") throw new Exception(sb.ToString());
            return ds;
        }
        #endregion
        Color LevelOneColor = Color.Green;
        Color LevelTwoColor = Color.FromArgb(201, 217, 243);
        Color LevelThreeColor = Color.FromArgb(231, 238, 248);
        Color LevelFourColor = Color.FromArgb(232, 230, 231);
        Color LevelFiveColor = Color.FromArgb(250, 252, 213);
        public List<DataSet> ReadExcelBySheetIndex(string FileName, int startRow, string str)
        {
            List<DataSet> listDs = new List<DataSet>();
            StringBuilder sb = new StringBuilder();
            using (FileStream stream = new FileStream(@FileName, FileMode.Open, FileAccess.Read))
            {
                IWorkbook workbook = WorkbookFactory.Create(stream);//使用接口,自动识别excel2003/2007格式
                //   ISheet sheet = workbook.GetSheetAt(SheetIndex);//得到里面第一个sheet
                List<string> listSheet = GetSheetNames(workbook);
                ISheet sheet;
                foreach (string sheetName in listSheet)
                {
                    DataSet ds = new DataSet("ds");
                    DataTable dt = new DataTable("dt");
                    sheet = workbook.GetSheet(sheetName);
                    if (!sheetName.Contains(str))
                    {
                        continue;
                    }
                    NPOI.SS.UserModel.IRow headerRow = sheet.GetRow(0);
                    int cellCount = headerRow.LastCellNum;
                    for (int j = 0; j < cellCount; j++)
                    {
                        NPOI.SS.UserModel.ICell cell = headerRow.GetCell(j);
                        dt.Columns.Add("F" + j.ToString());
                    }
                    int r = sheet.PhysicalNumberOfRows;
                    for (int i = (sheet.FirstRowNum); i <= 2900; i++)
                    {
                        NPOI.SS.UserModel.IRow row = null;
                        try
                        {
                            row = sheet.GetRow(i);
                            int ex = row.FirstCellNum;
                        }
                        catch (Exception)
                        {
                            continue;
                        }
                        DataRow dataRow = dt.NewRow();
                        for (int j = row.FirstCellNum; j < cellCount; j++)
                        {
                            try
                            {
                                if (row.GetCell(j) != null || row.GetCell(j).ToString() != "")
                                    //dataRow[j] = row.GetCell(j).ToString();
                                    dataRow[j] = GetCellData(row, j);
                            }
                            catch (Exception ex)
                            {
                                string s = ex.ToString();
                            }
                        }
                        dt.Rows.Add(dataRow);
                    }
                    ds.Tables.Add(dt);
                    listDs.Add(ds);
                }
                //   if (ds.Tables[0].Rows.Count == 0 && sb.ToString() != "") throw new Exception(sb.ToString());
            }
            return listDs;
        }
        public List<string> GetSheetNames(IWorkbook workbook)
        {
            int x = workbook.NumberOfSheets;
            List<string> sheetNames = new List<string>();
            for (int i = 0; i < x; i++)
            {
                sheetNames.Add(workbook.GetSheetName(i));
            }
            return sheetNames;
        }
        public object GetCellData(IRow row, int column)
        {
            try
            {
                ICell hs = row.GetCell(column);
                NpoiDataType datatype = GetCellDataType(hs); //NpoiDataType.Blank;
                object obj = row.GetCell(column) ?? null;
                if (datatype == NpoiDataType.Datetime)
                {
                    string v = "";
                    try
                    {
                        v = row.GetCell(column).StringCellValue;
                    }
                    catch (Exception e1)
                    {
                        v = row.GetCell(column).DateCellValue.ToString("yyyy-MM-dd hh:mm:ss");
                    }
                    if (v != "")
                    {
                        try
                        {
                            obj = row.GetCell(column).DateCellValue.ToString("yyyy-MM-dd hh:mm:ss");
                        }
                        catch (Exception e2)
                        {
                            obj = Convert.ToDateTime(v).ToString("yyyy-MM-dd hh:mm:ss");
                        }
                    }
                    else
                        obj = DBNull.Value;
                }
                else if (datatype == NpoiDataType.Numeric)
                {
                    obj = DBNull.Value;
                    try
                    {
                        //if (row.GetCell(column).StringCellValue != "")
                        obj = row.GetCell(column).NumericCellValue;
                    }
                    catch (Exception e3)
                    {
                        obj = row.GetCell(column).StringCellValue;
                    }
                }
                else if (datatype == NpoiDataType.String && hs.CellType == CellType.Formula)
                {
                    obj = row.GetCell(column).StringCellValue;
                }
                return obj;
            }
            catch (Exception e22)
            {
                return "";
            }
        }
        #region 从DataSet导出到MemoryStream流2003
        /// <summary>
        /// 从DataSet导出到MemoryStream流2003
        /// </summary>
        /// <param name="SaveFileName">文件保存路径</param>
        /// <param name="SheetName">Excel文件中的Sheet名称</param>
        /// <param name="ds">存储数据的DataSet</param>
        /// <param name="startRow">从哪一行开始写入,从0开始</param>
        /// <param name="datatypes">DataSet中的各列对应的数据类型</param>
        public bool CreateExcel2003(string SaveFileName, string SheetName, DataSet ds, int startRow, params NpoiDataType[] datatypes)
        {
            try
            {
                if (startRow < 0) startRow = 0;
                HSSFWorkbook wb = new HSSFWorkbook();
                wb = new HSSFWorkbook();
                DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
                dsi.Company = "pkm";
                SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
                si.Title =
                si.Subject = "automatic genereted document";
                si.Author = "pkm";
                wb.DocumentSummaryInformation = dsi;
                wb.SummaryInformation = si;
                ISheet sheet = wb.CreateSheet(SheetName);
                //sheet.SetColumnWidth(0, 50 * 256);
                //sheet.SetColumnWidth(1, 100 * 256);
                IRow row;
                ICell cell;
                DataRow dr;
                int j;
                int maxLength = 0;
                int curLength = 0;
                object columnValue;
                DataTable dt = ds.Tables[0];
                if (datatypes.Length < dt.Columns.Count)
                {
                    datatypes = new NpoiDataType[dt.Columns.Count];
                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        string dtcolumntype = dt.Columns[i].DataType.Name.ToLower();
                        switch (dtcolumntype)
                        {
                            case "string":
                                datatypes[i] = NpoiDataType.String;
                                break;
                            case "datetime":
                                datatypes[i] = NpoiDataType.Datetime;
                                break;
                            case "boolean":
                                datatypes[i] = NpoiDataType.Bool;
                                break;
                            case "double":
                                datatypes[i] = NpoiDataType.Numeric;
                                break;
                            default:
                                datatypes[i] = NpoiDataType.String;
                                break;
                        }
                    }
                }
                #region 创建表头
                row = sheet.CreateRow(0);//创建第i行
                ICellStyle style1 = wb.CreateCellStyle();//样式
                IFont font1 = wb.CreateFont();//字体
                font1.Color = HSSFColor.White.Index;//字体颜色
                font1.Boldweight = (short)FontBoldWeight.Bold;//字体加粗样式
                //style1.FillBackgroundColor = HSSFColor.WHITE.index;//GetXLColour(wb, LevelOneColor);// 设置图案色
                style1.FillForegroundColor = HSSFColor.Green.Index;//GetXLColour(wb, LevelOneColor);// 设置背景色
                style1.FillPattern = FillPattern.SolidForeground;
                style1.SetFont(font1);//样式里的字体设置具体的字体样式
                style1.Alignment = HorizontalAlignment.Center;//文字水平对齐方式
                style1.VerticalAlignment = VerticalAlignment.Center;//文字垂直对齐方式
                row.HeightInPoints = 25;
                for (j = 0; j < dt.Columns.Count; j++)
                {
                    columnValue = dt.Columns[j].ColumnName;
                    curLength = Encoding.Default.GetByteCount(columnValue.ToString());
                    maxLength = (maxLength < curLength ? curLength : maxLength);
                    int colounwidth = 256 * maxLength;
                    sheet.SetColumnWidth(j, colounwidth);
                    try
                    {
                        cell = row.CreateCell(j);//创建第0行的第j列
                        cell.CellStyle = style1;//单元格式设置样式
                        cell.SetCellType(CellType.String);
                        cell.SetCellValue(columnValue.ToString());
                    }
                    catch
                    {
                        continue;
                    }
                }
                #endregion
                #region 创建每一行
                for (int i = startRow; i < ds.Tables[0].Rows.Count; i++)
                {
                    dr = ds.Tables[0].Rows[i];
                    row = sheet.CreateRow(i + 1);//创建第i行
                    for (j = 0; j < dt.Columns.Count; j++)
                    {
                        columnValue = dr[j];
                        curLength = Encoding.Default.GetByteCount(columnValue.ToString());
                        maxLength = (maxLength < curLength ? curLength : maxLength);
                        int colounwidth = 256 * maxLength;
                        sheet.SetColumnWidth(j, colounwidth);
                        try
                        {
                            cell = row.CreateCell(j);//创建第i行的第j列
                            #region 插入第j列的数据
                            try
                            {
                                NpoiDataType dtype = datatypes[j];
                                switch (dtype)
                                {
                                    case NpoiDataType.String:
                                        {
                                            cell.SetCellType(CellType.String);
                                            cell.SetCellValue(columnValue.ToString());
                                        }
                                        break;
                                    case NpoiDataType.Datetime:
                                        {
                                            cell.SetCellType(CellType.String);
                                            cell.SetCellValue(columnValue.ToString());
                                        }
                                        break;
                                    case NpoiDataType.Numeric:
                                        {
                                            cell.SetCellType(CellType.Numeric);
                                            cell.SetCellValue(Convert.ToDouble(columnValue));
                                        }
                                        break;
                                    case NpoiDataType.Bool:
                                        {
                                            cell.SetCellType(CellType.Boolean);
                                            cell.SetCellValue(Convert.ToBoolean(columnValue));
                                        }
                                        break;
                                    case NpoiDataType.Richtext:
                                        {
                                            cell.SetCellType(CellType.Formula);
                                            cell.SetCellValue(columnValue.ToString());
                                        }
                                        break;
                                }
                            }
                            catch
                            {
                                cell.SetCellType(CellType.String);
                                cell.SetCellValue(columnValue.ToString());
                            }
                            #endregion
                        }
                        catch
                        {
                            continue;
                        }
                    }
                }
                #endregion
                //using (FileStream fs = new FileStream(@SaveFileName, FileMode.OpenOrCreate))//生成文件在服务器上
                //{
                //    wb.Write(fs);
                //}
                //string SaveFileName = "output.xls";
                using (FileStream fs = new FileStream(@SaveFileName, FileMode.OpenOrCreate, FileAccess.Write))//生成文件在服务器上
                {
                    wb.Write(fs);
                    Console.WriteLine("文件保存成功!" + SaveFileName);
                }
                return true;
            }
            catch (Exception er)
            {
                Console.WriteLine("文件保存成功!" + SaveFileName);
                return false;
            }
        }
        #endregion
        #region 从DataSet导出到MemoryStream流2007
        /// <summary>
        /// 从DataSet导出到MemoryStream流2007
        /// </summary>
        /// <param name="SaveFileName">文件保存路径</param>
        /// <param name="SheetName">Excel文件中的Sheet名称</param>
        /// <param name="ds">存储数据的DataSet</param>
        /// <param name="startRow">从哪一行开始写入,从0开始</param>
        /// <param name="datatypes">DataSet中的各列对应的数据类型</param>
        public bool CreateExcel2007(string SaveFileName, string SheetName, DataSet ds, int startRow, params NpoiDataType[] datatypes)
        {
            try
            {
                if (startRow < 0) startRow = 0;
                XSSFWorkbook wb = new XSSFWorkbook();
                ISheet sheet = wb.CreateSheet(SheetName);
                //sheet.SetColumnWidth(0, 50 * 256);
                //sheet.SetColumnWidth(1, 100 * 256);
                IRow row;
                ICell cell;
                DataRow dr;
                int j;
                int maxLength = 0;
                int curLength = 0;
                object columnValue;
                DataTable dt = ds.Tables[0];
                if (datatypes.Length < dt.Columns.Count)
                {
                    datatypes = new NpoiDataType[dt.Columns.Count];
                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        string dtcolumntype = dt.Columns[i].DataType.Name.ToLower();
                        switch (dtcolumntype)
                        {
                            case "string":
                                datatypes[i] = NpoiDataType.String;
                                break;
                            case "datetime":
                                datatypes[i] = NpoiDataType.Datetime;
                                break;
                            case "boolean":
                                datatypes[i] = NpoiDataType.Bool;
                                break;
                            case "double":
                                datatypes[i] = NpoiDataType.Numeric;
                                break;
                            default:
                                datatypes[i] = NpoiDataType.String;
                                break;
                        }
                    }
                }
                #region 创建表头
                row = sheet.CreateRow(0);//创建第i行
                ICellStyle style1 = wb.CreateCellStyle();//样式
                IFont font1 = wb.CreateFont();//字体
                font1.Color = HSSFColor.White.Index;//字体颜色
                font1.Boldweight = (short)FontBoldWeight.Bold;//字体加粗样式
                //style1.FillBackgroundColor = HSSFColor.WHITE.index;//GetXLColour(wb, LevelOneColor);// 设置图案色
                style1.FillForegroundColor = HSSFColor.Green.Index;//GetXLColour(wb, LevelOneColor);// 设置背景色
                style1.FillPattern = FillPattern.SolidForeground;
                style1.SetFont(font1);//样式里的字体设置具体的字体样式
                style1.Alignment = HorizontalAlignment.Center;//文字水平对齐方式
                style1.VerticalAlignment = VerticalAlignment.Center;//文字垂直对齐方式
                //row.HeightInPoints = 25;
                row.HeightInPoints = 15;
                for (j = 0; j < dt.Columns.Count; j++)
                {
                    columnValue = dt.Columns[j].ColumnName;
                    curLength = Encoding.Default.GetByteCount(columnValue.ToString());
                    maxLength = (maxLength < curLength ? curLength : maxLength);
                    int colounwidth = 256 * maxLength;
                    sheet.SetColumnWidth(j, colounwidth);
                    try
                    {
                        cell = row.CreateCell(j);//创建第0行的第j列
                        cell.CellStyle = style1;//单元格式设置样式
                        //cell.SetCellType(CellType.STRING);
                        cell.SetCellValue(columnValue.ToString());
                    }
                    catch
                    {
                        continue;
                    }
                }
                #endregion
                #region 创建每一行
                for (int i = startRow; i < ds.Tables[0].Rows.Count; i++)
                {
                    dr = ds.Tables[0].Rows[i];
                    row = sheet.CreateRow(i + 1);//创建第i行
                    for (j = 0; j < dt.Columns.Count; j++)
                    {
                        columnValue = dr[j];
                        curLength = Encoding.Default.GetByteCount(columnValue.ToString());
                        maxLength = (maxLength < curLength ? curLength : maxLength);
                        //int colounwidth = 256 * maxLength;
                        int colounwidth = 3000;
                        sheet.SetColumnWidth(j, colounwidth);
                        try
                        {
                            cell = row.CreateCell(j);//创建第i行的第j列
                            #region 插入第j列的数据
                            try
                            {
                                NpoiDataType dtype = datatypes[j];
                                switch (dtype)
                                {
                                    case NpoiDataType.String:
                                        {
                                            //cell.SetCellType(CellType.STRING);
                                            cell.SetCellValue(columnValue.ToString());
                                        }
                                        break;
                                    case NpoiDataType.Datetime:
                                        {
                                            // cell.SetCellType(CellType.STRING);
                                            cell.SetCellValue(columnValue.ToString());
                                        }
                                        break;
                                    case NpoiDataType.Numeric:
                                        {
                                            //cell.SetCellType(CellType.NUMERIC);
                                            cell.SetCellValue(Convert.ToDouble(columnValue));
                                        }
                                        break;
                                    case NpoiDataType.Bool:
                                        {
                                            //cell.SetCellType(CellType.BOOLEAN);
                                            cell.SetCellValue(Convert.ToBoolean(columnValue));
                                        }
                                        break;
                                    case NpoiDataType.Richtext:
                                        {
                                            // cell.SetCellType(CellType.FORMULA);
                                            cell.SetCellValue(columnValue.ToString());
                                        }
                                        break;
                                }
                            }
                            catch
                            {
                                //cell.SetCellType(HSSFCell.CELL_TYPE_STRING);
                                cell.SetCellValue(columnValue.ToString());
                            }
                            #endregion
                        }
                        catch
                        {
                            continue;
                        }
                    }
                }
                #endregion
                //using (FileStream fs = new FileStream(@SaveFileName, FileMode.OpenOrCreate))//生成文件在服务器上
                //{
                //    wb.Write(fs);
                //}
                //string SaveFileName = "output.xlsx";
                using (FileStream fs = new FileStream(SaveFileName, FileMode.OpenOrCreate, FileAccess.Write))//生成文件在服务器上
                {
                    wb.Write(fs);
                    Console.WriteLine("文件保存成功!" + SaveFileName);
                }
                return true;
            }
            catch (Exception er)
            {
                Console.WriteLine("文件保存失败!" + SaveFileName);
                return false;
            }
        }
        #endregion
        private short GetXLColour(HSSFWorkbook workbook, System.Drawing.Color SystemColour)
        {
            short s = 0;
            HSSFPalette XlPalette = workbook.GetCustomPalette();
            HSSFColor XlColour = XlPalette.FindColor(SystemColour.R, SystemColour.G, SystemColour.B);
            if (XlColour == null)
            {
                if (NPOI.HSSF.Record.PaletteRecord.STANDARD_PALETTE_SIZE < 255)
                {
                    if (NPOI.HSSF.Record.PaletteRecord.STANDARD_PALETTE_SIZE < 64)
                    {
                        //NPOI.HSSF.Record.PaletteRecord.STANDARD_PALETTE_SIZE= 64;
                        //NPOI.HSSF.Record.PaletteRecord.STANDARD_PALETTE_SIZE += 1;
                        XlColour = XlPalette.AddColor(SystemColour.R, SystemColour.G, SystemColour.B);
                    }
                    else
                    {
                        XlColour = XlPalette.FindSimilarColor(SystemColour.R, SystemColour.G, SystemColour.B);
                    }
                    s = XlColour.Indexed;
                }
            }
            else
                s = XlColour.Indexed;
            return s;
        }
        #region 读Excel-根据NpoiDataType创建的DataTable列的数据类型
        /// <summary>
        /// 读Excel-根据NpoiDataType创建的DataTable列的数据类型
        /// </summary>
        /// <param name="datatype"></param>
        /// <returns></returns>
        private Type GetDataTableType(NpoiDataType datatype)
        {
            Type tp = typeof(string);//Type.GetType("System.String")
            switch (datatype)
            {
                case NpoiDataType.Bool:
                    tp = typeof(bool);
                    break;
                case NpoiDataType.Datetime:
                    tp = typeof(DateTime);
                    break;
                case NpoiDataType.Numeric:
                    tp = typeof(double);
                    break;
                case NpoiDataType.Error:
                    tp = typeof(string);
                    break;
                case NpoiDataType.Blank:
                    tp = typeof(string);
                    break;
            }
            return tp;
        }
        #endregion
        #region 读Excel-得到不同数据类型单元格的数据
        /// <summary>
        /// 读Excel-得到不同数据类型单元格的数据
        /// </summary>
        /// <param name="datatype">数据类型</param>
        /// <param name="row">数据中的一行</param>
        /// <param name="column">哪列</param>
        /// <returns></returns>
        private object GetCellData(NpoiDataType datatype, IRow row, int column)
        {
            var objcell = row.GetCell(column);
            object obj = objcell ?? null;
            if (obj == null)
            {
                return null;
            }
            if (obj.ToString().Contains("月") && obj.ToString().Contains("-") && objcell.DateCellValue != null)
            {
                datatype = NpoiDataType.Datetime;
            }
            else if (objcell.CellType == CellType.Numeric && (obj.ToString().Contains("-") || obj.ToString().Contains("/")) && objcell.DateCellValue != null)
            {
                datatype = NpoiDataType.Datetime;
            }
            if (datatype == NpoiDataType.Datetime)
            {
                string v = "";
                try
                {
                    v = row.GetCell(column).StringCellValue.Trim();
                }
                catch (Exception e1)
                {
                    v = row.GetCell(column).DateCellValue.ToString("yyyy-MM-dd hh:mm:ss");
                }
                if (v != "")
                {
                    try
                    {
                        obj = row.GetCell(column).DateCellValue.ToString("yyyy-MM-dd hh:mm:ss");
                    }
                    catch (Exception e2)
                    {
                        obj = Convert.ToDateTime(v).ToString("yyyy-MM-dd hh:mm:ss");
                    }
                }
                else
                    obj = DBNull.Value;
            }
            else if (datatype == NpoiDataType.Numeric)
            {
                obj = DBNull.Value;
                try
                {
                    //if (row.GetCell(column).StringCellValue != "")
                    obj = row.GetCell(column).NumericCellValue;
                }
                catch (Exception e3)
                {
                    obj = row.GetCell(column).StringCellValue.Trim();
                }
            }
            else
            {
                if (obj != null)
                {
                    obj = obj.ToString().Trim().Replace("\n", "");//去掉回车,ligerui tree不支持回车
                    if (obj.ToString().StartsWith("."))
                    {
                        decimal.Parse("0" + obj.ToString());
                        obj = "0" + obj.ToString();
                    }
                }
            }
            return obj;
        }
        private object GetCellData_double(NpoiDataType datatype, IRow row, int column)
        {
            return (object)(row.GetCell(column).NumericCellValue) ?? null;
        }
        #endregion
        #region 获取单元格数据类型
        /// <summary>
        /// 获取单元格数据类型
        /// </summary>
        /// <param name="hs"></param>
        /// <returns></returns>
        private NpoiDataType GetCellDataType(ICell hs)
        {
            NpoiDataType dtype;
            DateTime t1;
            string cellvalue = "";
            switch (hs.CellType)
            {
                case CellType.Blank:
                    dtype = NpoiDataType.String;
                    cellvalue = hs.StringCellValue;
                    break;
                case CellType.Boolean:
                    dtype = NpoiDataType.Bool;
                    break;
                case CellType.Numeric:
                    dtype = NpoiDataType.String;
                    if (hs.NumericCellValue.ToString().Contains("-") || hs.NumericCellValue.ToString().Contains("/") || hs.ToString().Contains("-") || hs.ToString().Contains("/"))
                    {
                        hs.DateCellValue.ToString();
                        dtype = NpoiDataType.Datetime;
                    }
                    cellvalue = hs.NumericCellValue.ToString();
                    break;
                case CellType.String:
                    dtype = NpoiDataType.String;
                    cellvalue = hs.StringCellValue;
                    break;
                case CellType.Error:
                    dtype = NpoiDataType.Error;
                    break;
                case CellType.Formula:
                    {
                        dtype = NpoiDataType.String;
                        try
                        {
                            if (hs.CachedFormulaResultType == CellType.Numeric && hs.NumericCellValue.ToString() != "")
                            {
                                dtype = NpoiDataType.Numeric;
                                cellvalue = hs.NumericCellValue.ToString();
                            }
                            else if (hs.CachedFormulaResultType == CellType.Numeric && hs.DateCellValue.ToString() != "")
                            {
                                dtype = NpoiDataType.Datetime;
                                cellvalue = hs.DateCellValue.ToString();
                            }
                            else if (hs.RichStringCellValue.ToString() != "")
                            {
                                dtype = NpoiDataType.String;
                                cellvalue = hs.RichStringCellValue.ToString();
                            }
                        }
                        catch
                        {
                            try
                            {
                                if (hs.CachedFormulaResultType == CellType.Numeric && hs.NumericCellValue.ToString() != "")
                                {
                                    dtype = NpoiDataType.Numeric;
                                    cellvalue = hs.NumericCellValue.ToString();
                                }
                            }
                            catch
                            {
                                //cellvalue = hs.StringCellValue;
                            }
                        }
                        break;
                    }
                default:
                    dtype = NpoiDataType.Datetime;
                    break;
            }
            //if (cellvalue != "" && DateTime.TryParse(cellvalue, out t1)) dtype = NpoiDataType.Datetime;
            return dtype;
        }
        #endregion
        #region 测试代码
        #endregion
        public DataSet ReadExcel_ByColNum(string FileName, int startRow, int LastCellNum, params NpoiDataType[] ColumnDataType)
        {
            string colNamePix = "F";
            int ertime = 0;
            int intime = 0;
            DataSet ds = new DataSet("ds");
            DataTable dt = new DataTable("dt");
            DataRow dr;
            StringBuilder sb = new StringBuilder();
            using (FileStream stream = new FileStream(@FileName, FileMode.Open, FileAccess.Read))
            {
                IWorkbook workbook = WorkbookFactory.Create(stream);//使用接口,自动识别excel2003/2007格式
                ISheet sheet = workbook.GetSheetAt(0);//得到里面第一个sheet
                int j;
                IRow row;
                #region ColumnDataType赋值
                if (ColumnDataType.Length <= 0)
                {
                    row = sheet.GetRow(startRow - 1);//得到第i行
                    ColumnDataType = new NpoiDataType[LastCellNum];
                    for (int i = 0; i < LastCellNum; i++)
                    {
                        ICell hs = row.GetCell(i, MissingCellPolicy.CREATE_NULL_AS_BLANK);
                        ColumnDataType[i] = GetCellDataType(hs); //NpoiDataType.Blank;
                    }
                }
                #endregion
                for (j = 0; j < ColumnDataType.Length; j++)
                {
                    Type tp = GetDataTableType(ColumnDataType[j]);
                    dt.Columns.Add(colNamePix + j, tp);
                }
                ReadExcelEndRow = ReadExcelEndRow == 0 ? sheet.PhysicalNumberOfRows : ReadExcelEndRow;
                int ss = sheet.LastRowNum + 1;
                if (ReadExcelEndRow < ss && ReadExcelEndRow > 0)
                {
                    ReadExcelEndRow = ss;
                }
                for (int i = startRow - 1; i <= ReadExcelEndRow; i++)
                {
                    row = sheet.GetRow(i);//得到第i行
                    if (row == null) continue;
                    try
                    {
                        dr = dt.NewRow();
                        for (j = 0; j < ColumnDataType.Length; j++)
                        {
                            dr[colNamePix + (j)] = GetCellData(ColumnDataType[j], row, j);
                        }
                        dt.Rows.Add(dr);
                        intime++;
                    }
                    catch (Exception er)
                    {
                        ertime++;
                        sb.Append(string.Format("第{0}行出错:{1}\r\n", i + 1, er.Message));
                        continue;
                    }
                }
                ds.Tables.Add(dt);
            }
            if (ds.Tables[0].Rows.Count == 0 && sb.ToString() != "") throw new Exception(sb.ToString());
            return ds;
        }
    }
    #region 枚举(Excel单元格数据类型)
    /// <summary>
    /// 枚举(Excel单元格数据类型)
    /// </summary>
    public enum NpoiDataType
    {
        /// <summary>
        /// 字符串类型-值为1
        /// </summary>
        String,
        /// <summary>
        /// 布尔类型-值为2
        /// </summary>
        Bool,
        /// <summary>
        /// 时间类型-值为3
        /// </summary>
        Datetime,
        /// <summary>
        /// 数字类型-值为4
        /// </summary>
        Numeric,
        /// <summary>
        /// 复杂文本类型-值为5
        /// </summary>
        Richtext,
        /// <summary>
        /// 空白
        /// </summary>
        Blank,
        /// <summary>
        /// 错误
        /// </summary>
        Error
    }
    #endregion
}
WebAPI/Controllers/POOrderBillExcelController.cs
New file
@@ -0,0 +1,300 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using WebAPI.Code;
using WebAPI.Models;
namespace WebAPI.Controllers
{
    public class POOrderBillExcelController : ApiController
    {
        private JsonResult objJsonResult = new JsonResult();
        SQLHelper.ClsCNSRM oCn = new SQLHelper.ClsCNSRM();
        #region 采购订单 查询
        [Route("POOrderBillExcel/POOrderBillExcelList")]
        [HttpGet]
        public object POOrderBillExcelList(string sqlWhere)
        {
            DataSet ds = new DataSet();
            DataSet ds1 = new DataSet();
            DataTable dt = new DataTable();
            try
            {
                ds = oCn.RunProcReturn("select * from POOrderBill_Excel ", "POOrderBill_Excel");
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    ds1 = oCn.RunProcReturn($"exec h_p_POOrderBill_Excel {ds.Tables[0].Rows[i]["HQty"].ToString()},'{ds.Tables[0].Rows[i]["MaterialNum"].ToString()}'", "POOrderBill_Excel");
                    if (i == 0)
                    {
                        dt = ds1.Tables[0];
                    }
                    else
                    {
                        foreach (DataRow item in ds1.Tables[0].Rows)
                        {
                            DataRow dataRow = dt.NewRow();
                            dataRow.ItemArray = item.ItemArray;
                            dt.Rows.Add(dataRow);
                        }
                    }
                }
                objJsonResult.code = "1";
                objJsonResult.count = 1;
                objJsonResult.Message = "";
                objJsonResult.data = dt;
                return objJsonResult;
            }
            catch (Exception e)
            {
                objJsonResult.code = "0";
                objJsonResult.count = 0;
                objJsonResult.Message = "获取失败" + e.ToString();
                objJsonResult.data = null;
                return objJsonResult;
            }
        }
        #endregion
        #region 采购订单 文件上传
        [Route("POOrderBillExcel/POOrderBillExcelImport")]
        [HttpPost]
        public object POOrderBillExcelImport()
        {
            try
            {
                //获取文件名称
                var file = HttpContext.Current.Request.Files[0];
                //获取文件物理路径
                string ExcelPath = HttpContext.Current.Server.MapPath("~/" + file.FileName);
                //保存文件
                file.SaveAs(ExcelPath);
                NpoiHelper np = new NpoiHelper();
                DataSet ExcelDs = np.ReadExcel(ExcelPath, 1, 1, "2");
                //删除文件
                File.Delete(ExcelPath);
                //创建临时表
                DataTable tb2 = new DataTable("dt2");
                //添加列名
                for (int i = 0; i < ExcelDs.Tables[0].Columns.Count; i++)
                {
                    tb2.Columns.Add(ExcelDs.Tables[0].Rows[0][i].ToString());
                }
                //添加数据
                for (int i = 1; i < ExcelDs.Tables[0].Rows.Count; i++)
                {
                    DataRow row = tb2.NewRow();
                    for (int j = 0; j < ExcelDs.Tables[0].Columns.Count; j++)
                    {
                        row[j] = ExcelDs.Tables[0].Rows[i][j].ToString();
                    }
                    tb2.Rows.Add(row);
                }
                var error = "";
                //查询工艺路线没有的列
                if (!tb2.Columns.Contains("组织"))
                    error += "没有找到【组织】的标题,";
                if (!tb2.Columns.Contains("供应商"))
                    error += "没有找到【供应商】的标题,";
                if (!tb2.Columns.Contains("收料仓库"))
                    error += "没有找到【收料仓库】的标题,";
                if (!tb2.Columns.Contains("物料编码"))
                    error += "没有找到【物料编码】的标题,";
                if (!tb2.Columns.Contains("数量"))
                    error += "没有找到【数量】的标题,";
                if (!tb2.Columns.Contains("包装标识"))
                    error += "没有找到【包装标识】的标题,";
                if (error.Length > 0)
                {
                    objJsonResult.code = "0";
                    objJsonResult.count = 0;
                    objJsonResult.Message = $"Excel模板存在错误,{error}\r\n";
                    objJsonResult.data = null;
                    return objJsonResult;
                }
                //判断数据是否为空
                for (int i = 0; i < tb2.Rows.Count; i++)
                {
                    for (int j = 0; j < tb2.Columns.Count; j++)
                    {
                        if (tb2.Rows[i][j].ToString() == "")
                        {
                            objJsonResult.code = "0";
                            objJsonResult.count = 0;
                            objJsonResult.Message = $"Excel模板存在错误,第{(i + 1)}行第{(j + 1)}列值不能为空!\r\n";
                            objJsonResult.data = null;
                            return objJsonResult;
                        }
                    }
                }
                //检查物料 是否存在
                objJsonResult = (JsonResult)Checkdata(tb2);
                if (objJsonResult.code == "0")
                {
                    return objJsonResult;
                }
                else
                {
                    oCn.RunProc("delete from POOrderBill_Excel");
                    for (int i = 0; i < tb2.Rows.Count; i++)
                    {
                        oCn.RunProc("insert into POOrderBill_Excel(HItemID,HORGName, SupplierName, Warehouse_Shou," +
                            " MaterialNum, HQty, HPackFlag)values" +
                            $"({(i + 1)},'{tb2.Rows[i]["组织"].ToString()}', '{tb2.Rows[i]["供应商"].ToString()}', '{tb2.Rows[i]["收料仓库"].ToString()}', " +
                            $"'{tb2.Rows[i]["物料编码"].ToString()}', {tb2.Rows[i]["数量"].ToString()}, '{tb2.Rows[i]["包装标识"].ToString()}')");
                    }
                    objJsonResult.code = "1";
                    objJsonResult.count = 1;
                    objJsonResult.Message = error;
                    objJsonResult.data = tb2;
                    return objJsonResult;
                }
            }
            catch (Exception e)
            {
                objJsonResult.code = "0";
                objJsonResult.count = 0;
                objJsonResult.Message = "Exception!" + e.ToString();
                objJsonResult.data = null;
                return objJsonResult;
            }
        }
        //检查物料 是否存在
        private object Checkdata(DataTable dt)
        {
            DataSet ds = new DataSet();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                //组织
                ds = oCn.RunProcReturn("select * from Xt_ORGANIZATIONS where Hname='" + dt.Rows[i]["组织"].ToString() + "' ", "Xt_ORGANIZATIONS");
                if (ds.Tables[0].Rows.Count == 0)
                {
                    objJsonResult.code = "0";
                    objJsonResult.count = 0;
                    objJsonResult.Message = $"第{(i + 1)}行,组织为{dt.Rows[i]["组织"].ToString()}不存在!";
                    objJsonResult.data = null;
                    return objJsonResult;
                }
                //供应商
                ds = oCn.RunProcReturn("select * from Gy_Supplier where Hname='" + dt.Rows[i]["供应商"].ToString() + "' ", "Gy_Supplier");
                if (ds.Tables[0].Rows.Count == 0)
                {
                    objJsonResult.code = "0";
                    objJsonResult.count = 0;
                    objJsonResult.Message = $"第{(i + 1)}行,供应商为{dt.Rows[i]["供应商"].ToString()}不存在!";
                    objJsonResult.data = null;
                    return objJsonResult;
                }
                //收料仓库
                ds = oCn.RunProcReturn("select * from Gy_Warehouse where Hname='" + dt.Rows[i]["收料仓库"].ToString() + "' ", "Gy_Warehouse");
                if (ds.Tables[0].Rows.Count == 0)
                {
                    objJsonResult.code = "0";
                    objJsonResult.count = 0;
                    objJsonResult.Message = $"第{(i + 1)}行,收料仓库为{dt.Rows[i]["收料仓库"].ToString()}不存在!";
                    objJsonResult.data = null;
                    return objJsonResult;
                }
                //物料编码
                if (!DBUtility.ClsPub.AllowNumber(dt.Rows[i]["物料编码"].ToString()))
                {
                    objJsonResult.code = "0";
                    objJsonResult.count = 0;
                    objJsonResult.Message = "物料代码中不能出现连续‘.’并且首位末位不能为‘.’!";
                    objJsonResult.data = null;
                    return objJsonResult;
                }
                ds = oCn.RunProcReturn("select * from Gy_Material where HNumber='" + dt.Rows[i]["物料编码"].ToString() + "' ", "Gy_Material");
                if (ds.Tables[0].Rows.Count == 0)
                {
                    objJsonResult.code = "0";
                    objJsonResult.count = 0;
                    objJsonResult.Message = $"第{(i + 1)}行,物料编码为{dt.Rows[i]["物料编码"].ToString()}不存在!";
                    objJsonResult.data = null;
                    return objJsonResult;
                }
                //数量
                if (dt.Rows[i]["数量"].ToString() == "0")
                {
                    objJsonResult.code = "0";
                    objJsonResult.count = 0;
                    objJsonResult.Message = $"第{(i + 1)}行,数量不为0!";
                    objJsonResult.data = null;
                    return objJsonResult;
                }
                //判断导入物料的数量是否大于单据物料的总和数量
                ds = oCn.RunProcReturn("select * from h_v_POOrderBill_Excel " +
                    $"where 采购组织='{dt.Rows[i]["组织"].ToString()}' and 供应商='{dt.Rows[i]["供应商"].ToString()}' " +
                    $"and 包装标识='{dt.Rows[i]["包装标识"].ToString()}'" +
                    $"and 物料编码='{dt.Rows[i]["物料编码"].ToString()}' and 关闭状态='未关闭' and 审核状态='已审核' ", "h_v_POOrderBill_Excel");
                if (ds.Tables[0].Rows.Count != 0)
                {
                    double NumCount = 0;//总数量
                    foreach (DataRow item in ds.Tables[0].Rows)
                    {
                        NumCount += double.Parse(item["剩余收料数量"].ToString());
                    }
                    if (NumCount < double.Parse(dt.Rows[i]["数量"].ToString()))
                    {
                        objJsonResult.code = "0";
                        objJsonResult.count = 0;
                        objJsonResult.Message = $"第{(i + 1)}行导入数量大于采购订单合计数量,请找采购员申请做采购订单!";
                        objJsonResult.data = null;
                        return objJsonResult;
                    }
                }
                else
                {
                    objJsonResult.code = "0";
                    objJsonResult.count = 0;
                    objJsonResult.Message = $"第{(i + 1)}行,匹配不到物料信息!";
                    objJsonResult.data = null;
                    return objJsonResult;
                }
            }
            objJsonResult.code = "1";
            objJsonResult.count = 1;
            objJsonResult.Message = "没有问题";
            objJsonResult.data = null;
            return objJsonResult;
        }
        #endregion
    }
}
WebAPI/Web.config
@@ -58,6 +58,10 @@
        <assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.2.0.0" newVersion="4.2.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.0.1.0" newVersion="4.0.1.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>
WebAPI/WebAPI.csproj
@@ -43,6 +43,9 @@
    <Prefer32Bit>false</Prefer32Bit>
  </PropertyGroup>
  <ItemGroup>
    <Reference Include="BouncyCastle.Crypto, Version=1.8.9.0, Culture=neutral, PublicKeyToken=0e99375e54769942, processorArchitecture=MSIL">
      <HintPath>..\packages\Portable.BouncyCastle.1.8.9\lib\net40\BouncyCastle.Crypto.dll</HintPath>
    </Reference>
    <Reference Include="DAL, Version=1.0.0.0, Culture=neutral, processorArchitecture=x86">
      <SpecificVersion>False</SpecificVersion>
      <HintPath>..\..\SRM-MES\SRM-MES\DAL\bin\Debug\DAL.dll</HintPath>
@@ -50,6 +53,9 @@
    <Reference Include="DBUtility, Version=1.0.0.0, Culture=neutral, processorArchitecture=x86">
      <SpecificVersion>False</SpecificVersion>
      <HintPath>..\..\SRM-MES\SRM-MES\DAL\bin\Debug\DBUtility.dll</HintPath>
    </Reference>
    <Reference Include="ICSharpCode.SharpZipLib, Version=1.3.3.11, Culture=neutral, PublicKeyToken=1b03e6acf1164f73, processorArchitecture=MSIL">
      <HintPath>..\packages\SharpZipLib.1.3.3\lib\net45\ICSharpCode.SharpZipLib.dll</HintPath>
    </Reference>
    <Reference Include="Kingdee.BOS.WebApi.Client, Version=7.2.904.6, Culture=neutral, processorArchitecture=MSIL">
      <SpecificVersion>False</SpecificVersion>
@@ -80,11 +86,11 @@
    <Reference Include="Microsoft.Owin.Cors, Version=4.2.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
      <HintPath>..\packages\Microsoft.Owin.Cors.4.2.0\lib\net45\Microsoft.Owin.Cors.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.Owin.Host.SystemWeb, Version=2.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
      <HintPath>..\packages\Microsoft.Owin.Host.SystemWeb.2.1.0\lib\net45\Microsoft.Owin.Host.SystemWeb.dll</HintPath>
    <Reference Include="Microsoft.Owin.Host.SystemWeb, Version=4.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
      <HintPath>..\packages\Microsoft.Owin.Host.SystemWeb.4.0.1\lib\net45\Microsoft.Owin.Host.SystemWeb.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.Owin.Security, Version=2.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
      <HintPath>..\packages\Microsoft.Owin.Security.2.1.0\lib\net45\Microsoft.Owin.Security.dll</HintPath>
    <Reference Include="Microsoft.Owin.Security, Version=4.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
      <HintPath>..\packages\Microsoft.Owin.Security.4.0.1\lib\net45\Microsoft.Owin.Security.dll</HintPath>
    </Reference>
    <Reference Include="Microsoft.Web.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
      <HintPath>..\packages\Microsoft.Web.Infrastructure.1.0.0.0\lib\net40\Microsoft.Web.Infrastructure.dll</HintPath>
@@ -97,6 +103,18 @@
    <Reference Include="Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
      <SpecificVersion>False</SpecificVersion>
      <HintPath>..\..\..\..\WeChat Files\shenjie1112005\FileStorage\File\2019-12\webapi接口\FurjaFlatFormAPI\packages\Newtonsoft.Json.5.0.6\lib\net45\Newtonsoft.Json.dll</HintPath>
    </Reference>
    <Reference Include="NPOI, Version=2.5.6.0, Culture=neutral, PublicKeyToken=0df73ec7942b34e1, processorArchitecture=MSIL">
      <HintPath>..\packages\NPOI.2.5.6\lib\net45\NPOI.dll</HintPath>
    </Reference>
    <Reference Include="NPOI.OOXML, Version=2.5.6.0, Culture=neutral, PublicKeyToken=0df73ec7942b34e1, processorArchitecture=MSIL">
      <HintPath>..\packages\NPOI.2.5.6\lib\net45\NPOI.OOXML.dll</HintPath>
    </Reference>
    <Reference Include="NPOI.OpenXml4Net, Version=2.5.6.0, Culture=neutral, PublicKeyToken=0df73ec7942b34e1, processorArchitecture=MSIL">
      <HintPath>..\packages\NPOI.2.5.6\lib\net45\NPOI.OpenXml4Net.dll</HintPath>
    </Reference>
    <Reference Include="NPOI.OpenXmlFormats, Version=2.5.6.0, Culture=neutral, PublicKeyToken=0df73ec7942b34e1, processorArchitecture=MSIL">
      <HintPath>..\packages\NPOI.2.5.6\lib\net45\NPOI.OpenXmlFormats.dll</HintPath>
    </Reference>
    <Reference Include="Owin, Version=1.0.0.0, Culture=neutral, PublicKeyToken=f0ebd12fd5e55cc5, processorArchitecture=MSIL">
      <HintPath>..\packages\Owin.1.0\lib\net40\Owin.dll</HintPath>
@@ -192,10 +210,12 @@
    <Compile Include="Code\Test2.cs" />
    <Compile Include="Code\TestDAL.cs" />
    <Compile Include="Controllers\BarCodeController.cs" />
    <Compile Include="Controllers\NpoiHelper.cs" />
    <Compile Include="Controllers\POInStockBackController.cs" />
    <Compile Include="Controllers\POInStockController.cs" />
    <Compile Include="Controllers\PODemandPlanController.cs" />
    <Compile Include="Controllers\EntrustOrderController.cs" />
    <Compile Include="Controllers\POOrderBillExcelController.cs" />
    <Compile Include="Controllers\POOrderController.cs" />
    <Compile Include="Controllers\PublicPageMethodController.cs" />
    <Compile Include="Controllers\ReportController.cs" />
WebAPI/packages.config
@@ -4,10 +4,10 @@
  <package id="Microsoft.AspNet.Cors" version="5.0.0" targetFramework="net45" />
  <package id="Microsoft.AspNet.SignalR" version="2.4.2" targetFramework="net45" />
  <package id="Microsoft.AspNet.SignalR.Core" version="2.4.2" targetFramework="net45" />
  <package id="Microsoft.AspNet.SignalR.Core.zh-Hans" version="2.2.2" targetFramework="net45" />
  <package id="Microsoft.AspNet.SignalR.Core.zh-Hans" version="2.4.2" targetFramework="net45" />
  <package id="Microsoft.AspNet.SignalR.JS" version="2.4.2" targetFramework="net45" />
  <package id="Microsoft.AspNet.SignalR.SystemWeb" version="2.4.2" targetFramework="net45" />
  <package id="Microsoft.AspNet.SignalR.SystemWeb.zh-Hans" version="2.2.2" targetFramework="net45" />
  <package id="Microsoft.AspNet.SignalR.SystemWeb.zh-Hans" version="2.4.2" targetFramework="net45" />
  <package id="Microsoft.AspNet.SignalR.zh-Hans" version="2.2.2" targetFramework="net45" />
  <package id="Microsoft.AspNet.WebApi" version="5.2.3" targetFramework="net45" />
  <package id="Microsoft.AspNet.WebApi.Client" version="5.2.3" targetFramework="net45" />
@@ -19,14 +19,17 @@
  <package id="Microsoft.Azure.AppService.ApiApps.Service" version="0.9.16" targetFramework="net45" />
  <package id="Microsoft.Owin" version="4.2.0" targetFramework="net45" />
  <package id="Microsoft.Owin.Cors" version="4.2.0" targetFramework="net45" />
  <package id="Microsoft.Owin.Host.SystemWeb" version="2.1.0" targetFramework="net45" />
  <package id="Microsoft.Owin.Host.SystemWeb" version="4.0.1" targetFramework="net45" />
  <package id="Microsoft.Owin.Host.SystemWeb.zh-Hans" version="4.0.1" targetFramework="net45" />
  <package id="Microsoft.Owin.Security" version="2.1.0" targetFramework="net45" />
  <package id="Microsoft.Owin.Security" version="4.0.1" targetFramework="net45" />
  <package id="Microsoft.Owin.Security.zh-Hans" version="4.0.1" targetFramework="net45" />
  <package id="Microsoft.Owin.zh-Hans" version="4.0.1" targetFramework="net45" />
  <package id="Microsoft.Owin.zh-Hans" version="4.2.0" targetFramework="net45" />
  <package id="Microsoft.Web.Infrastructure" version="1.0.0.0" targetFramework="net45" />
  <package id="Newtonsoft.Json" version="6.0.4" targetFramework="net45" />
  <package id="NPOI" version="2.5.6" targetFramework="net45" />
  <package id="Owin" version="1.0" targetFramework="net45" />
  <package id="Portable.BouncyCastle" version="1.8.9" targetFramework="net45" />
  <package id="SharpZipLib" version="1.3.3" targetFramework="net45" />
  <package id="Swashbuckle" version="5.0.0" targetFramework="net45" />
  <package id="Swashbuckle.Core" version="5.0.0" targetFramework="net45" />
  <package id="System.IdentityModel.Tokens.Jwt" version="4.0.0" targetFramework="net45" />
WindowsFormsApp1/App.config
@@ -21,6 +21,10 @@
        <assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.2.0.0" newVersion="4.2.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.0.1.0" newVersion="4.0.1.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>