本帖最后由 刘洋 于 2023-2-20 01:49 编辑
我写了一个webAPI。
功能涉及到对excel文件的操作
代码中的地址用的是绝对地址c:\xxx\xx.xlsx
发布之前本地调试没问题。发布之后,调用API失败。
猜想一定是路径的问题(服务器的物理路径下已经放置了excel文件)。
问题就是:涉及到本地文件引用的API。路径应该怎么写。试过了url路径和本地路径,都不行。
附上c#代码和工程文件,跪求解决方案
- using System.Collections.Generic;
- using Excel = Microsoft.Office.Interop.Excel;
- using GrapeCity.Forguncy.ServerApi;
- using System.Diagnostics;
- using System;
- namespace excelforhzgpost
- {
- public class Class1 : ForguncyApi
- {
- [Post]
- public void excelforhzg()
- {
- var from = Context.Request.ReadFormAsync().Result;
- var path = from["path"][0];
- Excel.Application myApp = new Excel.Application();
- object missing = System.Reflection.Missing.Value;//设置object的默认值,需要添加名称空间using System.Reflection;
- //string path = @"http://127.0.0.1/xx/upload/priceList.xlsx";
- Excel.Workbook wb = myApp.Workbooks.Open(Convert.ToString(path));
- int sheetCount = wb.Worksheets.Count;//sheet数量
- for (int i = 1; i <= sheetCount; i++)
- {
- Excel.Worksheet ws = wb.Worksheets[i];
- string pinzhong = ws.Name;
- //int rows = ws.Rows.Count;//总行数
- //int cols = ws.Columns.Count;//总列数
- int rows = ws.UsedRange.CurrentRegion.Rows.Count;//总行数
- int cols = ws.UsedRange.CurrentRegion.Columns.Count;//总列数;
- for (int r = 3; r <= rows; r++)
- {
- string changdustr = Convert.ToString(ws.Rows[r].Cells[1].Value);//长度str
- for (int c = 2; c <= cols; c++)
- {
- string jg = Convert.ToString(ws.Rows[r].Cells[c].Value);//判断非空str
- string zhijingstr = ws.Rows[2].Cells[c].Value;//直径字符串
- if (changdustr != null && zhijingstr != null && jg != null)
- {
- int zhijing = int.Parse(System.Text.RegularExpressions.Regex.Replace(zhijingstr, @"[^0-9]+", ""));//直径int
- double changdu = double.Parse(changdustr);
- double jiage = double.Parse(jg);//价格
- this.DataAccess.AddTableData("产品价格表", new Dictionary<string, object>
- {
- {"产品编号", pinzhong },
- {"长度",changdu },
- {"直径",zhijing },
- {"标准价",jiage }
- });
- }
- }
- }
- }
- myApp.Quit();
- System.Runtime.InteropServices.Marshal.ReleaseComObject(myApp);
- myApp = null;
- //创建进程对象
- Process[] ExcelProcess = Process.GetProcessesByName("Excel");
- //关闭进程
- foreach (Process p in ExcelProcess)
- { p.Kill(); }
- }
- }
- }
复制代码
|