20220313 3张表格 导出excel功能

This commit is contained in:
路 范
2022-03-14 00:29:01 +08:00
parent 0c4a0efa74
commit a35cfa0819
430 changed files with 35219 additions and 0 deletions

View File

@@ -0,0 +1,32 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Threading.Tasks;
namespace TempTask.WebEntry.Tools
{
public class EnumHelper
{
/// <summary>
/// 得到枚举的DescriptionAttribute值。
/// </summary>
/// <typeparam name="TEnum"></typeparam>
/// <param name="value"></param>
/// <returns></returns>
static public string GetEnumDescription<TEnum>(object value)
{
Type enumType = typeof(TEnum);
if (!enumType.IsEnum)
throw new ArgumentException("不是枚举类型");
var name = Enum.GetName(enumType, value);
if (name == null)
return string.Empty;
object[] objs = enumType.GetField(name).GetCustomAttributes(typeof(DescriptionAttribute), false);
if (objs == null || objs.Length == 0)
return string.Empty;
DescriptionAttribute attr = objs[0] as DescriptionAttribute;
return attr.Description;
}
}
}

View File

@@ -0,0 +1,101 @@
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace TempTask.WebEntry.Tools
{
/// <summary>
///
/// </summary>
public static class ExcelHelper
{
static ExcelHelper()
{
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
}
/// <summary>
/// 判断是否为兼容模式
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
public static bool GetIsCompatible(string filePath)
{
return filePath.EndsWith(".xls", StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// 创建工作薄
/// </summary>
/// <param name="isCompatible"></param>
/// <returns></returns>
public static IWorkbook CreateWorkbook(bool isCompatible)
{
if (isCompatible)
{
return new HSSFWorkbook();
}
else
{
return new XSSFWorkbook();
}
}
/// <summary>
/// 创建工作薄(依据文件流)
/// </summary>
/// <param name="isCompatible"></param>
/// <param name="stream"></param>
/// <returns></returns>
public static IWorkbook CreateWorkbook(bool isCompatible, dynamic stream)
{
if (isCompatible)
{
return new HSSFWorkbook(stream);
}
else
{
return new XSSFWorkbook(stream);
}
}
/// <summary>
/// 列名字母转索引
/// </summary>
/// <param name="columnName"></param>
/// <returns></returns>
public static int ToExcelColumnIndex(this string columnName)
{
if (!Regex.IsMatch(columnName.ToUpper(), @"[A-Z]+")) { throw new Exception("invalid parameter"); }
int index = 0;
char[] chars = columnName.ToUpper().ToCharArray();
for (int i = 0; i < chars.Length; i++)
{
index += ((int)chars[i] - (int)'A' + 1) * (int)Math.Pow(26, chars.Length - i - 1);
}
return index - 1;
}
/// <summary>
/// 列索引转字母
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
public static string ToExcelColumnName(this int index)
{
if (index < 0) { throw new Exception("invalid parameter"); }
List<string> chars = new List<string>();
do
{
if (chars.Count > 0) index--;
chars.Insert(0, ((char)(index % 26 + (int)'A')).ToString());
index = (int)((index - index % 26) / 26);
} while (index > 0);
return String.Join(string.Empty, chars.ToArray());
}
}
}

View File

@@ -0,0 +1,24 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace TempTask.WebEntry.Tools
{
/// <summary>
/// 扩展
/// </summary>
public static class Extension
{
/// <summary>
/// 将字符串转换为整数
/// </summary>
/// <param name="str"></param>
/// <param name="defaultValue">转换失败时的默认值</param>
/// <returns></returns>
public static int ToInt(this string str, int defaultValue = int.MinValue)
{
return int.TryParse(str, out int i) ? i : defaultValue;
}
}
}

View File

@@ -0,0 +1,68 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace TempTask.WebEntry.Tools
{
/// <summary>
///
/// </summary>
public class HttpHelper
{
/// <summary>
/// 请求网页地址
/// </summary>
/// <param name="url">网页地址</param>
/// <param name="method"></param>
/// <param name="param">参数</param>
/// <returns></returns>
public static string CallUrl(string url, string method, string param)
{
//创建一个HTTP请求
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
//Post请求方式
request.Method = method;
//内容类型
request.ContentType = "application/json";
//byte[] bs = Encoding.ASCII.GetBytes(param); //参数转化为ascii码
byte[] bs = Encoding.UTF8.GetBytes(param);
request.ContentLength = bs.Length;
using (Stream reqStream = request.GetRequestStream())
{
reqStream.Write(bs, 0, bs.Length);
}
String strValue = "";//strValue为http响应所返回的字符流
HttpWebResponse response;
try
{
//获得响应流
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
response = ex.Response as HttpWebResponse;
}
using Stream s = response.GetResponseStream();
using StreamReader sr = new StreamReader(s);
strValue = sr.ReadToEnd();
return strValue;
}
/// <summary>
///
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public static string CallUrl(string url)
{
WebClient webClient = new WebClient();
return webClient.DownloadString(url);
}
}
}

View File

@@ -0,0 +1,146 @@
using Furion;
using Furion.FriendlyException;
using Furion.LinqBuilder;
using Newtonsoft.Json.Linq;
using NPOI.SS.UserModel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using TempTask.WebEntry.ApiController.Dto;
namespace TempTask.WebEntry.Tools
{
/// <summary>
///
/// </summary>
public class NumZjHelper
{
/// <summary>
///
/// </summary>
public enum ExcelType
{
/// <summary>
/// 总表
/// </summary>
[Description("总表(样表).xls")]
= 1,
/// <summary>
/// 城市更新
/// </summary>
[Description("住建系统抓投资情况通报(城市更新)样表.xlsx")]
= 2,
/// <summary>
/// 房地产业
/// </summary>
[Description("住建系统抓投资情况通报(房地产业+GDP支撑性指标样表.xlsx")]
= 3
}
/// <summary>
///
/// </summary>
/// <param name="year"></param>
/// <param name="month"></param>
/// <param name="week"></param>
/// <param name="excelType"></param>
/// <param name="sheets"></param>
/// <returns></returns>
public static string WriteTemplate(int year, int month, int week, ExcelType excelType, List<NumZjConfigSheet> sheets)
{
try
{
var _month = month.ToString().Length == 1 ? ("0" + month) : month.ToString();
int excelTypeInt = (int)excelType;
string template_name = EnumHelper.GetEnumDescription<ExcelType>(excelType);
string excelFilePath = $"{App.WebHostEnvironment.WebRootPath}\\ExcelTemplate\\{template_name}";
string outputPath = string.Empty;
if (!string.IsNullOrEmpty(excelFilePath))
{
using (FileStream excelFileStream = System.IO.File.OpenRead(excelFilePath))
{
bool isCompatible = ExcelHelper.GetIsCompatible(excelFilePath);
IWorkbook workbook = ExcelHelper.CreateWorkbook(isCompatible, excelFileStream);
foreach (var sheet_item in sheets)
{
if (sheet_item.url.IsNullOrEmpty())
continue;
ISheet sheet = null;
//if (int.TryParse(sheet_name.sheet_no, out sheetIndex))
//{
sheet = workbook.GetSheetAt(sheet_item.sheet_no - 1);
//}
//else
//{
// sheet = workbook.GetSheet(sheet_name.Value);
//}
var api_result = HttpHelper.CallUrl($"{sheet_item.url}?months={year}{_month}&w={week}");
var obj = JObject.Parse(api_result);
var datas = obj["data"] as JArray;
//从第几行开始 , 比如 行号是4 , 就写3
var startRowIndex = sheet_item.start_row - 1;
//当前已经跳了几行
int current_skip_count = 0;
for (int i = 0; i < sheet_item.null_row_count; i++)
{
if (i >= datas.Count + (sheet_item.skip_rows?.Count ?? 0))
break;
var c_rowindex = startRowIndex + i;
if (sheet_item.skip_rows != null && sheet_item.skip_rows.Contains(c_rowindex + 1))
{
current_skip_count++;
continue;
}
int cell_start_index = sheet_item.start_cell.ToExcelColumnIndex();
for (int x = cell_start_index; x < cell_start_index + sheet_item.null_cell_count; x++)
{
var column_letter = App.Configuration[$"column_name_match_{excelTypeInt}_{sheet_item.sheet_no}:{ x.ToExcelColumnName()}"];
if (string.IsNullOrWhiteSpace(column_letter))
continue;
var jtoken = datas[i - current_skip_count][column_letter];
var cellvalue = string.Empty;
if (jtoken.Type == JTokenType.Null)
cellvalue = "/";
else
cellvalue = jtoken.ToString();
sheet.GetRow(c_rowindex).GetCell(x).SetCellValue(cellvalue);
}
//var x = 0;
//foreach (var cell in cells)
//{
// if (x < sheet_item.skip)
// {
// x++;
// continue;
// }
// //if (cell.Value.ToString().StartsWith("3302"))
// // continue;
// if (x >= sheet_item.null_cell_count)
// continue;
// sheet.GetRow(c_rowindex).GetCell(sheet_item.start_cell.ToExcelColumnIndex() - 1 + x - sheet_item.skip).SetCellValue(cell.Value.ToString());
// x++;
//}
}
}
var file = new FileInfo(excelFilePath);
var savePath = file.DirectoryName + "\\OutPut\\";
if (!Directory.Exists(savePath))
Directory.CreateDirectory(savePath);
outputPath = savePath + year + "_" + _month + "_" + week + "_" + template_name;
using (var filess = new FileStream(outputPath, FileMode.Create, FileAccess.Write, FileShare.Read))
{
workbook.Write(filess);
}
}
}
return outputPath;
}
catch (System.IO.IOException ioex)
{
throw Oops.Oh("文件被占用,请检查文件模板");
}
}
}
}