1. Program Interface
Every time you need to deal with Excel files, are to go to Baidu to find a solution, really gas a fire, today a good summary, the next time you do not have to degree Niang.
I use WinForm to test, because WinForm is more convenient to test, in fact, as long as in the. NET platform, C # written programs, are universal.
2. Required DLLs
Npoi.zip contains all the required DLL files, which can be introduced into the project.
3. Code
public void Writeexcel (string readexcelpath, StringWriteexcelpath) {//Excel information to be read FileStream file = newFileStream (Readexcelpath, FileMode.Open, FileAccess.Read); Hssfworkbook book = newHssfworkbook (file); Hssfsheet sheet = (hssfsheet) book. Getsheetat (0); The Excel information that needs to be written Xssfworkbook is the FileStream WriteFile = new that processes xlsx or more files excel2007+FileStream (Writeexcelpath, FileMode.Open, FileAccess.Read); Xssfworkbook Writebook = newXssfworkbook (WriteFile); Xssfsheet Writesheet = (xssfsheet) writebook.getsheetat (0); for (int i = 0; i < sheet. Lastrownum + 1; i++) {
Get line I, get object IRow row = sheet. GetRow (i);
//New row I, and return the resulting object IRow Writerow = Writesheet.createrow (i); for (int j = 0; J < row. lastcellnum+1; J + + ) {Icell cell = row. Getcell (j); if (cell = = null ) {break ;}
//This sentence is to set the cell type to type string, otherwise if the cell contents are numeric, an exception row is thrown. Getcell (j). Setcelltype (celltype.string); String readvalue = sheet. GetRow (i). Getcell (j). Stringcellvalue; if (String . IsNullOrEmpty (ReadValue)) {continue ;}//New line I, Column J Writerow.createcell (j); Writesheet.getrow (i). Getcell (j). Setcellvalue (ReadValue); TextBox3.Text + = ReadValue;}}
//Save the address, I did the processing, do not let him save at my chosen address, actually do not deal with the words also no problem string savepath = TextBox2.Text.Replace (". xlsx", "_bak.xlsx" ); FileStream saveFile = new FileStream (Savepath, FileMode.Create);
//Save the processed file to a new file Writebook.write (saveFile ); Savefile.close (); File. Close (); MessageBox.Show ("finished with Excel" )}
3. Precautions
②irow Writerow = Writesheet.createrow (i); this sentence should be placed in the first layer of the loop outside, to take the IRow alone as a variable, and then in the inner loop can be called, otherwise, will cause only the last column to copy
C # (Winform,webform Universal) uses Npoi to copy xls files as xlsx files (modified, saved in Excel, including the processing of excel2003-office2007+)