This article mainly introduces C # application Npoi get the picture in Excel, save to the local algorithm. Have a good reference value, follow the small series together to see it
requirements: read the pictures in Excel, save to the specified path
Idea: Using Npoi getallpictures () method to obtain picture information
Steps:
1. Create a new Windows Forms application
2. Create a new Excel on the desktop and paste in two pictures
Such as:
3. Drag a button into the form
4. Click button, write in the Click event method, the method to read the picture: Exceltoimage
Click the event method as follows:
private string Exclepath = @ "C:\users\lenovo\Desktop\testPic.xls"; private void Button2_Click (object sender, EventArgs e) {list<string> Listpath = new list<string>{}; string SA Vepath = Path.Combine ("e:\\", "pic"); if (! Directory.Exists (Savepath))//Determine if there is a Save folder, no new Directory.CreateDirectory (Savepath); BOOL result = Exceltoimage (Exclepath, Savepath, ref Listpath); if (result) MessageBox.Show ("Export succeeded"); Else MessageBox.Show ("Export failed"); }
5. The Exceltoimage method event is as follows:
<summary>///Get pictures from Excel///</summary>//<param name= "filepath" > File paths </param>//< param name= "Savepath" > Picture save path </param>//<param name= "Listpath" > Return saved Chart address list</param>//< returns> Save picture Successful </returns> private bool Exceltoimage (string filepath,string savepath,ref list<string> Listpath) {try {using (FileStream Fsreader = File.openread (filepath)) {hssfworkbook wk = new Hssfworkbook (Fsreader); IList pictures = wk. Getallpictures (); int i = 0; foreach (hssfpicturedata pic in pictures) {//if (pic. Data.length = = 19504)//Skip the picture that does not need to be saved, where pic.data has picture length//continue; String ext = pic. Suggestfileextension ();//Gets the extension string path = string. Empty; if (ext. Equals ("jpg")) {Image jpg = image.fromstream (new MemoryStream (pic). Data);//from pic. The data stream creates the picture Path = Path.Combine (Savepath, String. Format ("Pic{0}.jpg", i++)); Jpg. Save (path);//Saving} else if (ext. Equals ("PNG")) {Image png = Image.fromstream (new MemoryStream (pic). Data)); Path = Path.Combine (Savepath, String. Format ("Pic{0}.png", i++)); Png. Save (path); } if (!string. IsNullOrEmpty (path)) Listpath.add (path); }}} catch (Exception ex) {return false; } return true; }
Results:
Note: This algorithm Hssfworkbook class, so the corresponding Excel should be 2003 before (including 2003) version, the extension is. xls.
Hssfworkbook: Is the version of the Operation Excel2003 before (including 2003), the extension is. xls
Xssfworkbook: Is the version of Operation Excel2007 +, the extension is. xlsx
The above is the C # application Npoi get the picture in Excel, save to the local algorithm's detailed introduction content, more related content please pay attention to topic.alibabacloud.com (www.php.cn)!