目录
背景
导出的文件类型是什么?
- 带分隔符的纯文本文件(扩展名为.csv,.txt,.gm等)
- Excel文件(.xls,.xlsx)
助手类
创建纯文件内容的扩展方法
使用此扩展名,我们将能够创建普通的文件内容作为一个string,考虑到一个输入DataTable。
扩展方法还具有以下选项:
- 设置分隔符
- 包括列名作为文件标题行
- 处理具有默认值的null值列
- 必要时修剪列值
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
public static class DataTableHelper
{
public static string DataTableToFileContent(this DataTable datatable,
string seperator = ",", bool inchuleColumnName = true,
string defaultNullColumnValue = "", bool trimColumValue = true)
{
/*https://stackoverflow.com/a/28503521 */
if (defaultNullColumnValue == null)
{
throw new NullReferenceException("'defaultNullColumnValue' should not be null");
}
StringBuilder sb = new StringBuilder();
/*header*/
if (inchuleColumnName)
{
for (int i = 0; i < datatable.Columns.Count; i++)
{
sb.Append(datatable.Columns[i]);
if (i < datatable.Columns.Count - 1)
{
sb.Append(seperator);
}
}
sb.AppendLine();
}
/*data*/
long lineNo = 0;
string value;
foreach (DataRow row in datatable.Rows)
{
lineNo++;
if (lineNo > 1)
{
sb.AppendLine();
}
for (int i = 0; i < datatable.Columns.Count; i++)
{
var columnValue = row[i];
value = columnValue == DBNull.Value ?
defaultNullColumnValue : columnValue.ToString();
if (trimColumValue)
{
value = value.Trim();
}
sb.Append(value);
if (i < datatable.Columns.Count - 1)
{
sb.Append(seperator);
}
}
}
return sb.ToString();
}
}
创建Excel文件对象的扩展方法
要创建Excel文件内容,我们使用EPPlus。这是一个很棒的库,具有许多很棒的功能和选项。不幸的是,它从版本5开始不再是免费版本,我们使用的是较低版本的4.5.3.3。
扩展方法还具有以下选项:
- 设置sheet名称
- 包括列名称作为标题,并自动过滤到标题行
- 处理具有默认值的null值列
- 必要时修剪列值
using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
public static class DataTableHelper
{
private static string GetExcelColumnName(int columnNumber)
{
/*
1 equal A
https://stackoverflow.com/questions/181596/
how-to-convert-a-column-number-e-g-127-into-an-excel-column-e-g-aa
*/
int dividend = columnNumber;
string columnName = String.Empty;
int modulo;
while (dividend > 0)
{
modulo = (dividend - 1) % 26;
columnName = Convert.ToChar(65 + modulo).ToString() + columnName;
dividend = (int)((dividend - modulo) / 26);
}
return columnName;
}
public static ExcelPackage DataTableToExcel(this DataTable datatable,
string sheetName = "Sheet1", bool inchuleColumnName = true,
string defaultNullColumnValue = null, bool trimColumValue = true)
{
if (String.IsNullOrEmpty(sheetName))
{
throw new NullReferenceException("'sheetName' should not be null or empty");
}
sheetName = sheetName.Trim();
ExcelPackage excel = new ExcelPackage();
var workSheet = excel.Workbook.Worksheets.Add(sheetName);
int columnCount = datatable.Columns.Count;
int lineNo = 1;
/*header*/
if (inchuleColumnName)
{
int headerNumber = 1;
foreach (DataColumn column in datatable.Columns)
{
workSheet.Cells[lineNo, headerNumber].Value = column.ColumnName;
headerNumber++;
}
workSheet.Row(lineNo).Style.Font.Bold = true;
/*add filter to header*/
workSheet.Cells[String.Format("{0}{1}:{2}{3}", GetExcelColumnName(1),
lineNo, GetExcelColumnName(columnCount), lineNo)].AutoFilter = true;
lineNo++;
}
/*data*/
string value;
foreach (DataRow row in datatable.Rows)
{
for (int i = 0; i < columnCount; i++)
{
var columnValue = row[i];
value = columnValue == DBNull.Value ?
defaultNullColumnValue : columnValue.ToString();
if (trimColumValue && value != null)
{
value = value.Trim();
}
int columnNo = i + 1;
/*https://stackoverflow.com/a/36824090*/
workSheet.Cells[lineNo, columnNo].Value =
string.IsNullOrEmpty(value) ? null : value;
}
lineNo++;
}
for (int i = 1; i <= columnCount; i++)
{
workSheet.Column(i).AutoFit();
}
return excel;
}
}
让我们将代码添加到我们现有的扩展帮助类中。
文件助手
这是一个小的文件/目录/路径帮助程序类。在这里,我们将使用如下方法:
- DeleteFileIfExists(string filePath) 删除文件(如果存在)
- WriteAllText(string filePath, string contents) 在具有特定内容的位置创建一个新文件
using System.IO;
public class FileSystemHelper
{
/// <summary>
/// string p1 = "c:\\temp\\";
/// string p2 = "\\subdir\\file\\";
/// to c:\temp\subdir\file
/// </summary>
public static string CombineDirectory(string rootDirectoryPath, string childDirectoryPath)
{
rootDirectoryPath = rootDirectoryPath.TrimEnd('\\');
childDirectoryPath = childDirectoryPath.Trim('\\');
return Path.Combine(rootDirectoryPath, childDirectoryPath);
}
/// <summary>
/// string p1 = "c:\\temp\\";
/// string p2 = "\\file.txt";
/// to c:\temp\file.txt
/// </summary>
public static string CombineFile(string rootDirectoryPath, string filePathOrName)
{
rootDirectoryPath = rootDirectoryPath.TrimEnd('\\');
filePathOrName = filePathOrName.Trim('\\');
return Path.Combine(rootDirectoryPath, filePathOrName);
}
public static void CreateDirectoryIfNotExists(string directoryPath)
{
if (!DirectoryExists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
}
public static void DeleteFileIfExists(string filePath)
{
if (FileExists(filePath))
{
File.Delete(filePath);
}
}
public static bool DirectoryExists(string directoryPath)
{
return Directory.Exists(directoryPath);
}
public static bool FileExists(string filePath)
{
return File.Exists(filePath);
}
/*file*/
public static void MoveFile(string fromFilePath, string toFilePath)
{
File.Move(fromFilePath, toFilePath);
}
public static void WriteAllText(string filePath, string contents)
{
/*create file if doesn't exist*/
File.WriteAllText(filePath, contents);
}
}
其他方法也很有用,因此也请看一看。
使用代码
创建普通文件
在这里,我们正在创建一个CSV文件。
string filePath = @"c:\dataTable.csv";
DataTable dataTable = Data.Instance.DataTable;
FileSystemHelper.DeleteFileIfExists(filePath);
FileSystemHelper.WriteAllText(filePath, dataTable.DataTableToFileContent());
要使用其他扩展名(如txt),我们只需将文件名更改为“dataTable.txt ”。
创建Excel文件
在这里,我们正在创建一个XLSX文件。
string filePath = @"c:\dataTable.xlsx";
DataTable dataTable = Data.Instance.DataTable;
FileSystemHelper.DeleteFileIfExists(filePath);
using (var excel = dataTable.DataTableToExcel())
{
excel.SaveAs(new FileInfo(filePath));
}
我相信XLS也可以,只需更改扩展名并尝试一下即可。
解决方案和项目
它是Visual Studio 2015解决方案和.NET Framework 4.5
局限性
- 列值将使用ToString()方法转换为string。因此,DateTime, decimal, float或其他seminar数据类型会话转到string可能与预期不符。我们需要首先创建一个格式化DataTable对象。
- 列号,顺序或名称也需要预先格式化。
- 这可能不是创建大文件的最有效方法。
下一步是什么?
- 创建XML,doc和pdf文件
- ASP.NET响应示例