C#保存wps和office表格.数据源为list<T>类型

想要操作wps或office表格需要引入相对应的dll,office好找,wps在扩展中找到kingsoft的一些dll.

其中通过特性描述来获取泛型的中文名.

具体实现代码如下:  

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Reflection;
using System.IO;

using ET;
using Microsoft.Office.Interop.Excel;
using System.Diagnostics;
using System.ComponentModel;

namespace src.Common
{
public class SaveExcel
{
public static string Save<T>(List<T> list, string name, string saveWay, string tableHead)
{
try
{
SaveWPSExcel<T>(list, name, saveWay, tableHead);
return "WPS保存成功";

}
catch (Exception ex)
{
try
{
SaveOfficeExcel<T>(list, name, saveWay, tableHead);
return "office保存成功";
}
catch (Exception ex1)
{
return "请安装office或WPS";
}
}
}

/// <summary>
/// 保存wps表格
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="list">数据源列表</param>
/// <param name="name">文件名</param>
/// <param name="saveWay">保存路径</param>
/// <param name="tableHead">表头</param>
/// <returns></returns>
public static string SaveWPSExcel<T>(List<T> list, string name, string saveWay, string tableHead)
{
string message = "";

ET.ApplicationClass xlsApp = new ET.ApplicationClass();
if (xlsApp == null)
{
message = "您没有安装WPS,请安装后再次使用!";
return message;
}
ET.Application objExcel = new ET.Application();

objExcel.Visible = false;

object missing = System.Reflection.Missing.Value;
workbook objBook = (workbook)objExcel.Workbooks.Add(missing);
ET.Worksheet objSheet = (ET.Worksheet)objBook.Worksheets.get_Item(1);
ET.Range objRange;

Type t = typeof(T);

string last = ToName(t.GetProperties().Count() - 1);

int stateRow = 3;
if (list.Count == 0)
{
message = "没有数据传入,无需保存";
}
else
{
objRange = objSheet.get_Range("A1", last + "1");
objRange.Merge(true);
objRange.HorizontalAlignment = ET.ETHAlign.etHAlignCenter;
objRange = objSheet.get_Range("A1", missing);
objRange.Value2 = tableHead;
objRange.Font.Size = 20;
objRange.Font.Bold = true;

int titleIndex = 1;
foreach (PropertyInfo p in t.GetProperties())
{
DescriptionAttribute attr = (DescriptionAttribute)p.GetCustomAttributes(typeof(DescriptionAttribute), true).FirstOrDefault();
if (attr != null)
{
objSheet.Cells[(stateRow - 1), titleIndex++] = attr.Description;
}
else
{
objSheet.Cells[(stateRow - 1), titleIndex++] = p.Name;
}
//objSheet.Cells[(stateRow - 1), titleIndex++] =((DescriptionAttribute)Attribute.GetCustomAttribute(p,typeof(DescriptionAttribute))).Description;
}

int iRow = stateRow;
foreach (T info in list)
{
int icel = 1;
foreach (PropertyInfo p in t.GetProperties())
{
objSheet.Cells[iRow, icel++] = p.GetValue(info, null).ToString();
}
iRow++;
//int icel = 1;
//for (int iCol = 1; iCol < t.GetProperties().Count(); iCol++)
//{
// objSheet.Cells[iRow, icel++] = dr[iCol].ToString();
//}
//iRow++;
}
objRange = objSheet.get_Range("A2", last + "2");
objRange.Cells.Interior.Color = System.Drawing.Color.FromArgb(255, 204, 153).ToArgb();
objRange.HorizontalAlignment = ET.ETHAlign.etHAlignCenter;

objRange = objSheet.get_Range("A3", last + iRow.ToString());
objRange.EntireColumn.AutoFit();
objRange.HorizontalAlignment = ET.ETHAlign.etHAlignLeft;

objRange = objSheet.get_Range("A" + (iRow + 1).ToString(), last + (iRow + 1).ToString());
objRange.Merge(true);
objRange.Value2 = DateTime.Now.ToString();
objRange.HorizontalAlignment = ET.ETHAlign.etHAlignRight;
objRange.Cells.Interior.Color = System.Drawing.Color.FromArgb(255, 204, 153).ToArgb();
}

objBook.Saved = true;
DateTime dtime = DateTime.Now;
string fileName = dtime.ToString("yyyy-MM-dd-HH-mm-ss") + ".xlsx";
string baseWay = System.AppDomain.CurrentDomain.BaseDirectory;
string fileWay = baseWay + saveWay + "\\" + name + fileName;
objBook.SaveCopyAs(fileWay);
objBook.Close(true, Type.Missing, Type.Missing);
objExcel = null;
xlsApp.Quit();
xlsApp = null;
//KillProcess("et");
message = "已将信息保存到“" + saveWay + "”文件夹下";
return message;
}
/// <summary>
/// 保存excel表格
/// </summary>
/// <param name="table">表数据</param>
/// <param name="name">保存的文件名</param>
/// <param name="saveWay">保存路径</param>
/// <param name="tableHead">表头内容</param>
/// <param name="title">列名数组</param>
/// <returns></returns>
public static string SaveOfficeExcel<T>(List<T> list, string name, string saveWay, string tableHead)
{
string message = "";

Microsoft.Office.Interop.Excel.ApplicationClass xlsApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
if (xlsApp == null)
{
message = "您没有安装Microsoft Offic Excel,请安装后再次使用!";
return message;
}

Microsoft.Office.Interop.Excel.Application objExcel = new Microsoft.Office.Interop.Excel.Application();

objExcel.Visible = false;

object missing = System.Reflection.Missing.Value;
Workbook objBook = objExcel.Workbooks.Add(missing);
Microsoft.Office.Interop.Excel.Worksheet objSheet = (Microsoft.Office.Interop.Excel.Worksheet)objBook.Worksheets.get_Item(1);
Microsoft.Office.Interop.Excel.Range objRange;

Type t = typeof(T);
string last = ToName(t.GetProperties().Count() - 1);

int stateRow = 3;
if (list.Count == 0)
{
message = "没有数据传入,无需保存";
}
else
{
objRange = objSheet.get_Range("A1", last + "1");
objRange.Merge(0);
objRange.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
objRange = objSheet.get_Range("A1", missing);
objRange.Value2 = tableHead;
objRange.Font.Size = 20;
objRange.Font.Bold = true;

int titleIndex = 1;
foreach (PropertyInfo p in t.GetProperties())
{
DescriptionAttribute attr = (DescriptionAttribute)p.GetCustomAttributes(typeof(DescriptionAttribute), true).FirstOrDefault();
if (attr != null)
{
objSheet.Cells[(stateRow - 1), titleIndex++] = attr.Description;
}
else
{
objSheet.Cells[(stateRow - 1), titleIndex++] = p.Name;
}
}

int iRow = stateRow;
foreach (T info in list)
{
int icel = 1;
foreach (PropertyInfo p in t.GetProperties())
{
objSheet.Cells[iRow, icel++] = p.GetValue(info, null);
}
iRow++;
//int icel = 1;
//for (int iCol = 1; iCol < t.GetProperties().Count(); iCol++)
//{
// objSheet.Cells[iRow, icel++] = dr[iCol].ToString();
//}
//iRow++;
}
objRange = objSheet.get_Range("A2", last + "2");
objRange.Cells.Interior.Color = System.Drawing.Color.FromArgb(255, 204, 153).ToArgb();
objRange.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;

objRange = objSheet.get_Range("A3", last + iRow.ToString());
objRange.EntireColumn.AutoFit();
objRange.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft;

objRange = objSheet.get_Range("A" + (iRow + 1).ToString(), last + (iRow + 1).ToString());
objRange.Merge(0);
objRange.Value2 = DateTime.Now.ToString();
objRange.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignRight;
objRange.Cells.Interior.Color = System.Drawing.Color.FromArgb(255, 204, 153).ToArgb();
}

objBook.Saved = true;
DateTime dtime = DateTime.Now;
string fileName = dtime.ToString("yyyy-MM-dd-HH-mm-ss") + ".xlsx";
string baseWay = System.AppDomain.CurrentDomain.BaseDirectory;
string fileWay = baseWay + saveWay + "\\" + name + fileName;
objBook.SaveCopyAs(fileWay);
objBook.Close(true, Type.Missing, Type.Missing);
objExcel = null;
xlsApp.Quit();
xlsApp = null;
KillProcess("Excel");
message = "已将信息保存到“" + saveWay + "”文件夹下";
return message;
}
/// <summary>
/// 关闭excel
/// </summary>
/// <param name="processName"></param>
private static void KillProcess(string processName)
{
System.Diagnostics.Process myproc = new System.Diagnostics.Process();
//得到所有打开的进程
try
{
foreach (Process thisproc in Process.GetProcessesByName(processName))
{
if (!thisproc.CloseMainWindow())
{
thisproc.Kill();
}
}
}
catch (Exception Exc)
{
throw new Exception("", Exc);
}
}
/// <summary>
/// 将数字转换成字母
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
public static string ToName(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());
}
}
}

C#保存wps和office表格.数据源为list<T>类型

时间: 2024-10-18 00:10:25

C#保存wps和office表格.数据源为list<T>类型的相关文章

C#操作WPS和office兼容性的问题

http://blog.csdn.net/yanpengliumin/article/details/50344799 最近一直在做的开发是关于导出word的功能,一开始的做法是在VS中直接添加引用office PIA,Microsoft.Office.Interop.Word,VS08有两个版本,V11和V12,V11对应的是office03,V12对应的office07,试验之后得出结论,这两个PIA的引用只会影响开发机器的使用,就是说要与开发机器的office版本相对应.在目标机器上都是可

WPS中删除表格的左右边框

选定你已经做好的表格,选定最左边一列,点表格->表格属性->边框和底纹,选边框,在右边的预览里点一下左边的线即可,右边同理操作. 效果如下: 步骤如下: 1)用鼠标选中左边的一列,右击"边框和底纹"-->在"边框"选项卡里,点击-->确定: 图2 删除左边框 2)同理,用鼠标选中右边的一列,右击"边框和底纹"-->在"边框"选项卡里,点击-->确定:   WPS中删除表格的左右边框,布布扣,

同是办公软件,wps和office有什么区别?

今天完美小编为大家带来的是wps和office有什么区别教程,那么到底有什么区别呢?相信很多朋友都模棱两可,说不出所以然,看看下面的教程,相信你会选择更适合你的那一款软件.一起来看看吧! 1.两者特点 WPS是新兴的一款国内OFFICE软件,以其美观大方,界面清晰,软件小巧,操作适合国人习惯而风靡.微软OFFICE则秉承微软软件的强大,办公处理能力强大而著称. 2.差别 对于差别我只提大家最关心的,那就是他们在"办公功能"上基本无差,所以选择这两款软件的原因不在于它的功能,而在于其他细

【xlwings】 wps 和 office 的excel creat_sheet区别

最近在学习 xlwings,参考学习的网址:https://www.jianshu.com/p/b534e0d465f7 写得很棒,学到了很多. 在新建sheet表单, 发现一个问题. import xlwings as xw def creat_sheet(path, sheet=None, before=None): ''' :param path: excel file path :param sheet: the name of which creating the sheet, cou

webform 不实用office控件导出excel StringBuilder 类型拼接字符串表格导出excel

StringBuilder sb = new StringBuilder(); sb.AppendLine("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=gb2312\">"); sb.AppendLine("<table border=\"1\">"); sb.Append("<tr&

ubuntu安装WPS替代office

安装 1.下载地址:http://community.wps.cn/download/(去WPS官网下载) 下载第一个即可 2.执行安装命令: sudo dpkg -i wps-office_10.1.0.5672~a21_amd64.deb 解决字体缺失问题 1.下载:http://vdisk.weibo.com/s/ajLw30suHpSUg?from=page_100505_profile&wvr=6 2.创建目录: sudo mkdir /usr/share/fonts/wps-offi

WPS和Office压缩word文档图片大小

来自为知笔记(Wiz)

Spring MVC动态切换数据源(多数据库类型)

最近由于项目需求,需要将Sql Server 和 Mysql 两种数据库整合到一个项目,项目的用到的框架是SSM. 因此尝试了利用AOP切面来切每次执行的Servcie方法,根据Service所在的包名来实现数据源自动切换. 1.项目架构如下: 2.在com.jiefupay.database包中建立四个类: 其中 DataSourceContextHolder.java类源码如下: package com.jiefupay.datebase; public class DataSourceCo

WPS Office 2016 for Mac中文版 v1.0.0

WPS Office 2016 for Mac中文版点击下载WPS Office 2016 for Mac中文版是一款由金山软件股份有限公司自主研发的一款办公软件套装,可以实现办公软件最常用的文字.表格.演示等多种功能.具有内存占用低.运行速度快.体积小巧.强大插件平台支持.免费提供海量在线存储空间及文档模板.支持阅读和输出PDF文件.全面兼容微软Office97-2010格式(doc/docx/xls/xlsx/ppt/pptx等)独特优势.覆盖Windows.Linux.Android.iO