C#儲存wps和office表格.資料來源為list<T>類型

來源:互聯網
上載者:User

標籤:des   color   使用   os   檔案   資料   io   for   

想要操作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());
}
}
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.