需要注意的是NPOI读取xlsx格式文件会报错,目前没找到解决,如果有谁了解也可以提供下,导出与写入xlsx目前暂时没啥问题
1、首先文件的一些处理
#region 文件处理类
/*************文件处理类*************/
public class NiceFileProduce
{
//分解路径用枚举
public enum DecomposePathEnum
{
PathOnly = 0,//仅返回路径
NameAndExtension = 1,//返回文件名+扩展名
NameOnly = 2,//仅返回文件名
ExtensionOnly = 3,//仅返回扩展名(带.)
}
//------------【函数:将文件路径分解】------------
//filePath文件路径
//DecomposePathEnum返回类型
//------------------------------------------------
public static string DecomposePathAndName(string filePath, DecomposePathEnum
decomposePathEnum)
{
string result = "";
switch (decomposePathEnum)
{
case DecomposePathEnum.PathOnly://仅返回路径
result = filePath.Substring(0, filePath.LastIndexOf("\\"));
break;
case DecomposePathEnum.NameAndExtension://返回文件名+扩展名
result = filePath.Substring(filePath.LastIndexOf("\\") + 1);
break;
case DecomposePathEnum.NameOnly://仅返回文件名
result = filePath.Substring(filePath.LastIndexOf("\\") + 1,
filePath.LastIndexOf(".") - filePath.LastIndexOf("\\") - 1);
break;
case DecomposePathEnum.ExtensionOnly://仅返回扩展名(带.)
result = filePath.Substring(filePath.LastIndexOf("."));
break;
default://
result = "";
break;
}
return result;
}
//------------【函数:判断文件路径是否存在,不存在则创建】------------
//filePath文件夹路径
//DecomposePathEnum返回类型
//---------------------------------------------------------------------
public static string CheckAndCreatPath(string path)
{
if (Directory.Exists(path))
{
return path;
}
else
{
if (path.LastIndexOf("\\") <= 0)
{
try
{
Directory.CreateDirectory(path);
return path;
}
catch
{
return "error";
}
}
else
{
if (CheckAndCreatPath(DecomposePathAndName(path,
DecomposePathEnum.PathOnly)) == "error")
{
return "error";
}
else
{
Directory.CreateDirectory(path);
return path;
}
}
}
}
}
#endregion
2、将DataGridView表格保存到csv文档
#region 将表格控件保存至Excel文件(新建/替换
//------------【函数:将表格控件保存至Excel文件(新建/替换)】------------
//filePath要保存的目标Excel文件路径名
//datagGridView要保存至Excel的表格控件
//------------------------------------------------------------------------
public static bool SaveToExcelNew(string filePath, DataGridView dataGridView)
{
bool result = true;
FileStream fs = null;//创建一个新的文件流
HSSFWorkbook workbook = null;//创建一个新的Excel文件
ISheet sheet = null;//为Excel创建一张工作表
//定义行数、列数、与当前Excel已有行数
int rowCount = dataGridView.RowCount;//记录表格中的行数
int colCount = dataGridView.ColumnCount;//记录表格中的列数
//判断文件夹是否存在
if (NiceFileProduce.CheckAndCreatPath(NiceFileProduce.DecomposePathAndName(filePath, NiceFileProduce.DecomposePathEnum.PathOnly)) == "error")
{
result = false;
return result;