C # Save the WPS and Office tables. The data source is of the List <t> type.

Source: Internet
Author: User

If you want to operate WPS or office tables, you need to introduce the corresponding DLL. for office, WPS can find some DLL of Kingsoft in expansion.

The feature description is used to obtain the generic Chinese name.

The specific implementation code is as follows:

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
{
Savew1_xcel <t> (list, name, saveway, tablehead );
Return "WPS saved successfully ";

}
Catch (exception ex)
{
Try
{
Saveofficeexcel <t> (list, name, saveway, tablehead );
Return "The Office is successfully saved ";
}
Catch (exception ex1)
{
Return "Please install office or Wps ";
}
}
}


/// <Summary>
/// Save the WPS table
/// </Summary>
/// <Typeparam name = "T"> type </typeparam>
/// <Param name = "list"> data source list </param>
/// <Param name = "name"> file name </param>
/// <Param name = "saveway"> Save path </param>
/// <Param name = "tablehead"> header </param>
/// <Returns> </returns>
Public static string savew1_xcel <t> (list <t> list, string name, string saveway, string tablehead)
{
String message = "";

Et. applicationclass xlsapp = new et. applicationclass ();
If (xlsapp = NULL)
{
Message = "You have not installed WPS. Please use it again after installation! ";
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 = "no data passed in, no need to save ";
}
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 = "the information has been saved to the" + saveway + "folder ";
Return message;
}
/// <Summary>
/// Save the Excel file
/// </Summary>
/// <Param name = "table"> table data </param>
/// <Param name = "name"> saved file name </param>
/// <Param name = "saveway"> Save path </param>
/// <Param name = "tablehead"> header content </param>
/// <Param name = "title"> array of column names </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 = "You have not installed Microsoft offic excel. Please use it again after installation! ";
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 = "no data passed in, no need to save ";
}
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 = "the information has been saved to the" + saveway + "folder ";
Return message;
}
/// <Summary>
/// Close Excel
/// </Summary>
/// <Param name = "processname"> </param>
Private Static void killprocess (string processname)
{
System. Diagnostics. Process myproc = new system. Diagnostics. Process ();
// Obtain all opened Processes
Try
{
Foreach (process thisproc in process. getprocessesbyname (processname ))
{
If (! Thisproc. closemainwindow ())
{
Thisproc. Kill ();
}
}
}
Catch (exception exc)
{
Throw new exception ("", exc );
}
}
/// <Summary>
/// Convert a number into a letter
/// </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 ());
}
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.