tijian_tieying/web/Common/DataToExcel.cs
2025-02-20 12:14:39 +08:00

651 lines
24 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Diagnostics;
using System.Collections;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Excel;
using System.Collections.Generic;
using System.IO;
using NPOI.SS.UserModel;
using NPOI.HSSF.UserModel;
using NPOI.SS.Format;
using NPOI.SS.Formula.Functions;
using static NPOI.HSSF.Util.HSSFColor;
namespace ZWL.Common
{
/// <summary>
/// 操作EXCEL导出数据报表的类
/// 张为龙
/// 2008.4
/// </summary>
public class DataToExcel
{
public DataToExcel()
{
}
#region EXCEL的一个类(Excel.dll支持)
private int titleColorindex = 15;
/// <summary>
/// 标题背景色
/// </summary>
public int TitleColorIndex
{
set { titleColorindex = value; }
get { return titleColorindex; }
}
private DateTime beforeTime; //Excel启动之前时间
private DateTime afterTime; //Excel启动之后时间
#region Excel示例
/// <summary>
/// 创建一个Excel示例
/// </summary>
public void CreateExcel()
{
Excel.Application excel = new Excel.Application();
excel.Application.Workbooks.Add(true);
excel.Cells[1, 1] = "第1行第1列";
excel.Cells[1, 2] = "第1行第2列";
excel.Cells[2, 1] = "第2行第1列";
excel.Cells[2, 2] = "第2行第2列";
excel.Cells[3, 1] = "第3行第1列";
excel.Cells[3, 2] = "第3行第2列";
//保存
excel.ActiveWorkbook.SaveAs("./tt.xls", XlFileFormat.xlExcel9795, null, null, false, false, Excel.XlSaveAsAccessMode.xlNoChange, null, null, null, null, null);
//打开显示
excel.Visible = true;
// excel.Quit();
// excel=null;
// GC.Collect();//垃圾回收
}
#endregion
#region DataTable的数据导出显示为报表
/// <summary>
/// 将DataTable的数据导出显示为报表
/// </summary>
/// <param name="dt">要导出的数据</param>
/// <param name="strTitle">导出报表的标题</param>
/// <param name="FilePath">保存文件的路径</param>
/// <returns></returns>
public string OutputExcel(System.Data.DataTable dt, string strTitle, string FilePath)
{
beforeTime = DateTime.Now;
Excel.Application excel;
Excel._Workbook xBk;
Excel._Worksheet xSt;
int rowIndex = 4;
int colIndex = 1;
excel = new Excel.ApplicationClass();
xBk = excel.Workbooks.Add(true);
xSt = (Excel._Worksheet)xBk.ActiveSheet;
//取得列标题
foreach (DataColumn col in dt.Columns)
{
colIndex++;
excel.Cells[4, colIndex] = col.ColumnName;
//设置标题格式为居中对齐
xSt.get_Range(excel.Cells[4, colIndex], excel.Cells[4, colIndex]).Font.Bold = true;
xSt.get_Range(excel.Cells[4, colIndex], excel.Cells[4, colIndex]).HorizontalAlignment = Excel.XlVAlign.xlVAlignCenter;
xSt.get_Range(excel.Cells[4, colIndex], excel.Cells[4, colIndex]).Select();
xSt.get_Range(excel.Cells[4, colIndex], excel.Cells[4, colIndex]).Interior.ColorIndex = titleColorindex;//19;//设置为浅黄色共计有56种
}
//取得表格中的数据
foreach (DataRow row in dt.Rows)
{
rowIndex++;
colIndex = 1;
foreach (DataColumn col in dt.Columns)
{
colIndex++;
if (col.DataType == System.Type.GetType("System.DateTime"))
{
excel.Cells[rowIndex, colIndex] = (Convert.ToDateTime(row[col.ColumnName].ToString())).ToString("yyyy-MM-dd");
xSt.get_Range(excel.Cells[rowIndex, colIndex], excel.Cells[rowIndex, colIndex]).HorizontalAlignment = Excel.XlVAlign.xlVAlignCenter;//设置日期型的字段格式为居中对齐
}
else
if (col.DataType == System.Type.GetType("System.String"))
{
excel.Cells[rowIndex, colIndex] = "'" + row[col.ColumnName].ToString();
xSt.get_Range(excel.Cells[rowIndex, colIndex], excel.Cells[rowIndex, colIndex]).HorizontalAlignment = Excel.XlVAlign.xlVAlignCenter;//设置字符型的字段格式为居中对齐
}
else
{
excel.Cells[rowIndex, colIndex] = row[col.ColumnName].ToString();
}
}
}
//加载一个合计行
int rowSum = rowIndex + 1;
int colSum = 2;
excel.Cells[rowSum, 2] = "合计";
xSt.get_Range(excel.Cells[rowSum, 2], excel.Cells[rowSum, 2]).HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
//设置选中的部分的颜色
xSt.get_Range(excel.Cells[rowSum, colSum], excel.Cells[rowSum, colIndex]).Select();
//xSt.get_Range(excel.Cells[rowSum,colSum],excel.Cells[rowSum,colIndex]).Interior.ColorIndex =Assistant.GetConfigInt("ColorIndex");// 1;//设置为浅黄色共计有56种
//取得整个报表的标题
excel.Cells[2, 2] = strTitle;
//设置整个报表的标题格式
xSt.get_Range(excel.Cells[2, 2], excel.Cells[2, 2]).Font.Bold = true;
xSt.get_Range(excel.Cells[2, 2], excel.Cells[2, 2]).Font.Size = 22;
//设置报表表格为最适应宽度
xSt.get_Range(excel.Cells[4, 2], excel.Cells[rowSum, colIndex]).Select();
xSt.get_Range(excel.Cells[4, 2], excel.Cells[rowSum, colIndex]).Columns.AutoFit();
//设置整个报表的标题为跨列居中
xSt.get_Range(excel.Cells[2, 2], excel.Cells[2, colIndex]).Select();
xSt.get_Range(excel.Cells[2, 2], excel.Cells[2, colIndex]).HorizontalAlignment = Excel.XlHAlign.xlHAlignCenterAcrossSelection;
//绘制边框
xSt.get_Range(excel.Cells[4, 2], excel.Cells[rowSum, colIndex]).Borders.LineStyle = 1;
xSt.get_Range(excel.Cells[4, 2], excel.Cells[rowSum, 2]).Borders[Excel.XlBordersIndex.xlEdgeLeft].Weight = Excel.XlBorderWeight.xlThick;//设置左边线加粗
xSt.get_Range(excel.Cells[4, 2], excel.Cells[4, colIndex]).Borders[Excel.XlBordersIndex.xlEdgeTop].Weight = Excel.XlBorderWeight.xlThick;//设置上边线加粗
xSt.get_Range(excel.Cells[4, colIndex], excel.Cells[rowSum, colIndex]).Borders[Excel.XlBordersIndex.xlEdgeRight].Weight = Excel.XlBorderWeight.xlThick;//设置右边线加粗
xSt.get_Range(excel.Cells[rowSum, 2], excel.Cells[rowSum, colIndex]).Borders[Excel.XlBordersIndex.xlEdgeBottom].Weight = Excel.XlBorderWeight.xlThick;//设置下边线加粗
afterTime = DateTime.Now;
//显示效果
//excel.Visible=true;
//excel.Sheets[0] = "sss";
ClearFile(FilePath);
string filename = DateTime.Now.ToString("yyyyMMddHHmmssff") + ".xls";
excel.ActiveWorkbook.SaveAs(FilePath + filename, Excel.XlFileFormat.xlExcel9795, null, null, false, false, Excel.XlSaveAsAccessMode.xlNoChange, null, null, null, null, null);
//wkbNew.SaveAs strBookName;
//excel.Save(strExcelFileName);
#region Excel进程
//需要对Excel的DCOM对象进行配置:dcomcnfg
//excel.Quit();
//excel=null;
xBk.Close(null, null, null);
excel.Workbooks.Close();
excel.Quit();
//注意这里用到的所有Excel对象都要执行这个操作否则结束不了Excel进程
// if(rng != null)
// {
// System.Runtime.InteropServices.Marshal.ReleaseComObject(rng);
// rng = null;
// }
// if(tb != null)
// {
// System.Runtime.InteropServices.Marshal.ReleaseComObject(tb);
// tb = null;
// }
if (xSt != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(xSt);
xSt = null;
}
if (xBk != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(xBk);
xBk = null;
}
if (excel != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
excel = null;
}
GC.Collect();//垃圾回收
#endregion
return filename;
}
#endregion
#region Kill Excel进程
/// <summary>
/// 结束Excel进程
/// </summary>
public void KillExcelProcess()
{
Process[] myProcesses;
DateTime startTime;
myProcesses = Process.GetProcessesByName("Excel");
//得不到Excel进程ID暂时只能判断进程启动时间
foreach (Process myProcess in myProcesses)
{
startTime = myProcess.StartTime;
if (startTime > beforeTime && startTime < afterTime)
{
myProcess.Kill();
}
}
}
#endregion
#endregion
#region DataTable的数据导出显示为报表(使Excel对象使COM.Excel)
#region 使
public static void GridViewToExcel(DataSet MyData, Hashtable nameList,string ReportTitle)
{
string FilePath = System.Web.HttpContext.Current.Server.MapPath("../") + "ReportFile\\";
//利用excel对象
DataToExcel dte = new DataToExcel();
string filename = "";
try
{
if (MyData.Tables[0].Rows.Count > 0)
{
filename = dte.DataExcel(MyData.Tables[0], ReportTitle, FilePath, nameList);
}
}
catch
{}
if (filename != "")
{
System.Web.HttpContext.Current.Response.Redirect("../ReportFile/" + filename, true);
}
}
#endregion
/// <summary>
/// 将DataTable的数据导出显示为报表(不使用Excel对象)
/// </summary>
/// <param name="dt">数据DataTable</param>
/// <param name="strTitle">标题</param>
/// <param name="FilePath">生成文件的路径</param>
/// <param name="nameList"></param>
/// <returns></returns>
public string DataExcel(System.Data.DataTable dt, string strTitle, string FilePath, Hashtable nameList)
{
COM.Excel.cExcelFile excel = new COM.Excel.cExcelFile();
ClearFile(FilePath);
//string filename = DateTime.Now.ToString("yyyyMMddHHmmssff") + ".xls";
string filename = strTitle + ".xls";
excel.CreateFile(FilePath + filename);
excel.PrintGridLines = false;
COM.Excel.cExcelFile.MarginTypes mt1 = COM.Excel.cExcelFile.MarginTypes.xlsTopMargin;
COM.Excel.cExcelFile.MarginTypes mt2 = COM.Excel.cExcelFile.MarginTypes.xlsLeftMargin;
COM.Excel.cExcelFile.MarginTypes mt3 = COM.Excel.cExcelFile.MarginTypes.xlsRightMargin;
COM.Excel.cExcelFile.MarginTypes mt4 = COM.Excel.cExcelFile.MarginTypes.xlsBottomMargin;
double height = 1.5;
excel.SetMargin(ref mt1, ref height);
excel.SetMargin(ref mt2, ref height);
excel.SetMargin(ref mt3, ref height);
excel.SetMargin(ref mt4, ref height);
COM.Excel.cExcelFile.FontFormatting ff = COM.Excel.cExcelFile.FontFormatting.xlsNoFormat;
string font = "宋体";
short fontsize = 9;
excel.SetFont(ref font, ref fontsize, ref ff);
byte b1 = 1,
b2 = 12;
short s3 = 12;
excel.SetColumnWidth(ref b1, ref b2, ref s3);
string header = "页眉";
string footer = "页脚";
excel.SetHeader(ref header);
excel.SetFooter(ref footer);
COM.Excel.cExcelFile.ValueTypes vt = COM.Excel.cExcelFile.ValueTypes.xlsText;
COM.Excel.cExcelFile.CellFont cf = COM.Excel.cExcelFile.CellFont.xlsFont0;
COM.Excel.cExcelFile.CellAlignment ca = COM.Excel.cExcelFile.CellAlignment.xlsCentreAlign;
COM.Excel.cExcelFile.CellHiddenLocked chl = COM.Excel.cExcelFile.CellHiddenLocked.xlsNormal;
// 报表标题
int cellformat = 1;
// int rowindex = 1,colindex = 3;
// object title = (object)strTitle;
// excel.WriteValue(ref vt, ref cf, ref ca, ref chl,ref rowindex,ref colindex,ref title,ref cellformat);
int rowIndex = 1;//起始行
int colIndex = 0;
//取得列标题
foreach (DataColumn colhead in dt.Columns)
{
colIndex++;
string name = colhead.ColumnName.Trim();
object namestr = (object)name;
IDictionaryEnumerator Enum = nameList.GetEnumerator();
while (Enum.MoveNext())
{
if (Enum.Key.ToString().Trim() == name)
{
namestr = Enum.Value;
}
}
excel.WriteValue(ref vt, ref cf, ref ca, ref chl, ref rowIndex, ref colIndex, ref namestr, ref cellformat);
}
//取得表格中的数据
foreach (DataRow row in dt.Rows)
{
rowIndex++;
colIndex = 0;
foreach (DataColumn col in dt.Columns)
{
colIndex++;
if (col.DataType == System.Type.GetType("System.DateTime"))
{
object str = (object)(Convert.ToDateTime(row[col.ColumnName].ToString())).ToString("yyyy-MM-dd"); ;
excel.WriteValue(ref vt, ref cf, ref ca, ref chl, ref rowIndex, ref colIndex, ref str, ref cellformat);
}
else
{
object str = (object)row[col.ColumnName].ToString();
excel.WriteValue(ref vt, ref cf, ref ca, ref chl, ref rowIndex, ref colIndex, ref str, ref cellformat);
}
}
}
int ret = excel.CloseFile();
// if(ret!=0)
// {
// //MessageBox.Show(this,"Error!");
// }
// else
// {
// //MessageBox.Show(this,"请打开文件c:\\test.xls!");
// }
return filename;
}
#endregion
#region Excel文件
private void ClearFile(string FilePath)
{
String[] Files = System.IO.Directory.GetFiles(FilePath);
if (Files.Length > 10)
{
for (int i = 0; i < 10; i++)
{
try
{
System.IO.File.Delete(Files[i]);
}
catch
{
}
}
}
}
#endregion
#region excel文件
/// <summary>
/// 读取excel
/// </summary>
/// <param name="path1"></param>
/// <param name="Excel_Name"></param>
/// <returns></returns>
public static System.Data.DataTable Reader_Excel(string path1, string Excel_Name)
{
try
{
//实例化DataTable来存放数据
System.Data.DataTable dt = new System.Data.DataTable();
string fileName = path1 + Excel_Name;
string sheetName = Excel_Name;//Excel的工作表名称
bool isColumnName = true;//判断第一行是否为标题列
IWorkbook workbook;//创建一个工作薄接口
string fileExt = Path.GetExtension(fileName).ToLower();//获取文件的拓展名
//创建一个文件流
using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
if (fileExt == ".xls" || fileExt == ".xlsx")//xlsx
{
//.xls ,xlsx
//XSSFWorkbook workbook = new XSSFWorkbook(file);
//HSSFWorkbook workbook = new HSSFWorkbook(file);
workbook = new HSSFWorkbook(fs);
}
else
{
workbook = null;
}
//实例化sheet
ISheet sheet = null;
if (sheetName != null && sheetName != "")//判断是否存在sheet
{
sheet = workbook.GetSheet(sheetName);
if (sheet == null)
{
sheet = workbook.GetSheetAt(0);//从第一个开始读取0位索引
}
else
{
sheet = workbook.GetSheetAt(0);
}
}
//获取表头
IRow header = sheet.GetRow(sheet.FirstRowNum);
int startRow = 0;//数据的第一行索引
if (isColumnName)//表示第一行是列名
{
startRow = sheet.FirstRowNum + 1;//数据从第二行开始读
//遍历表的第一行,即所有的列名
for (int i = header.FirstCellNum; i < header.LastCellNum; i++)
{
ICell cell = header.GetCell(i);
if (cell != null)
{
//获取列名的值
string cellValue = cell.ToString();
if (cellValue != null)
{
DataColumn col = new DataColumn(cellValue);
dt.Columns.Add(col);
}
else
{
DataColumn col = new DataColumn();
dt.Columns.Add(col);
}
}
}
}
//读取数据
for (int i = startRow; i <= sheet.LastRowNum; i++)
{
IRow row = sheet.GetRow(i);
if (row == null)
{
continue;
}
DataRow dr = dt.NewRow();
for (int j = row.FirstCellNum; j < row.LastCellNum; j++)
{
if (row.GetCell(j) != null)
{
dr[j] = row.GetCell(j).ToString();
}
}
dt.Rows.Add(dr);
}
return dt;
}
}
catch (Exception e)
{
throw e;
}
}
#endregion
/// <summary>
/// 将datatable写入到excel(xls)
/// 2023-11-23 xulu
/// </summary>
/// <param name="dt">datatable</param>
/// <param name="filepath">写入的文件路径</param>
/// <returns></returns>
public static bool DataTableToExcel(System.Data.DataTable dt, string filepath, Hashtable nameList)
{
bool result = false;
IWorkbook workbook = null;
FileStream fs = null;
IRow row = null;
ISheet sheet = null;
ICell cell = null;
try
{
if (!File.Exists(filepath))
{
fs=File.Create(filepath);//创建文件
fs.Close();
}
if (dt != null && dt.Rows.Count > 0)
{
workbook = new HSSFWorkbook();
sheet = workbook.CreateSheet("Sheet0");//创建一个名称为Sheet0的表
sheet.DefaultRowHeight=30 * 20;
int rowCount = dt.Rows.Count;//行数
int columnCount = dt.Columns.Count;//列数
// 每列列宽字典
var dic = new Dictionary<int, int>();
// 标题及内容单元格样式
var headCellStyle = CreateCellStyle(workbook, true);
var contentCellStyle = CreateCellStyle(workbook, false);
//设置列头
row = sheet.CreateRow(0);//excel第一行设为列头
for (int c = 0; c < columnCount; c++)
{
cell = row.CreateCell(c);
string name = dt.Columns[c].ColumnName;
object namestr = (object)name;
IDictionaryEnumerator Enum = nameList.GetEnumerator();
while (Enum.MoveNext())
{
if (Enum.Key.ToString().Trim() == name)
{
namestr = Enum.Value;
}
}
cell.SetCellValue(namestr.ToString());
cell.CellStyle = headCellStyle;
dic.Add(c, System.Text.Encoding.Default.GetBytes(cell.StringCellValue).Length * 256 + 1000);
}
//设置每行每列的单元格,
for (int i = 0; i < rowCount; i++)
{
row = sheet.CreateRow(i + 1);
for (int j = 0; j < columnCount; j++)
{
cell = row.CreateCell(j);//excel第二行开始写入数据
cell.SetCellValue(dt.Rows[i][j].ToString());
cell.CellStyle = contentCellStyle;
int length = System.Text.Encoding.Default.GetBytes(cell.StringCellValue).Length * 256 + 1000;
length = length > 15000 ? 15000 : length;
// 若比已存在列宽更宽则替换Excel限制最大宽度为15000
if (dic[j] < length)
{
dic[j] = length;
}
}
}
for (int i = 0; i < dt.Columns.Count; i++)
{
sheet.SetColumnWidth(i, dic[i]);
}
using (fs = File.OpenWrite(filepath))
{
workbook.Write(fs);//向打开的这个xls文件中写入数据
result = true;
fs.Close();
}
}
return result;
}
catch (Exception ex)
{
//MessageBox.Show(ex.Message);
if (fs != null)
{
fs.Close();
}
return false;
}
}
/// <summary>
/// 单元格样式
/// 2023-11-23 xulu
/// </summary>
/// <param name="workbook"></param>
/// <param name="isHead"></param>
/// <returns></returns>
private static ICellStyle CreateCellStyle(IWorkbook workbook, bool isHead)
{
var cellStyle = workbook.CreateCellStyle();
var font = workbook.CreateFont();
font.IsBold = isHead; // 粗体
font.FontHeightInPoints = 12;
font.FontName = "宋体";
cellStyle.SetFont(font);
cellStyle.Alignment = HorizontalAlignment.Center; // 水平居中
cellStyle.VerticalAlignment = VerticalAlignment.Center; // 垂直居中
cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
cellStyle.WrapText = true;//内容自动换行,避免存在换行符的内容合并成单行
return cellStyle;
}
}
}