csharp: read excel using Aspose.Cells
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 | /// <summary> /// /// </summary> /// <param name="strFileName"></param> /// <returns></returns> public static System.Data.DataTable ReadExcel(String strFileName) { Workbook book = new Workbook(strFileName); //book.Open(strFileName); //老版本 Worksheet sheet = book.Worksheets[0]; Cells cells = sheet.Cells; return cells.ExportDataTableAsString(0, 0, cells.MaxDataRow + 1, cells.MaxDataColumn + 1, true ); } /// <summary> /// /// </summary> /// <param name="strFileName"></param> /// <param name="sheetname"></param> /// <returns></returns> public static System.Data.DataTable ReadExcel(String strFileName, string sheetname) { Workbook book = new Workbook(strFileName); //book.Open(strFileName);//老版本 Worksheet sheet = book.Worksheets[sheetname]; Cells cells = sheet.Cells; return cells.ExportDataTableAsString(0, 0, cells.MaxDataRow + 1, cells.MaxDataColumn + 1, true ); } /// <summary> /// 读取工作表 /// 涂聚文 /// 20150228 /// </summary> /// <param name="strFileName"></param> /// <param name="comb"></param> public static void ReadExcelCombox(String strFileName, System.Windows.Forms.ComboBox comb) { comb.Items.Clear(); Workbook book = new Workbook(strFileName); // book.Open(strFileName);//老版本 Worksheet sheet = book.Worksheets[0]; for ( int i = 0; i < book.Worksheets.Count; i++) { comb.Items.Add(book.Worksheets[i].Name.ToString()); } // Cells cells = sheet.Cells; //return cells.ExportDataTableAsString(0, 0, cells.MaxDataRow + 1, cells.MaxDataColumn + 1, true); } /// <summary> /// DataTable导出到EXCEL /// http://www.aspose.com/docs/display/cellsnet/Aspose.Cells+Object+Model /// http://www.aspose.com/docs/display/cellsnet/Converting+Worksheet+to+Image+and+Worksheet+to+Image+by+Page /// </summary> /// <param name="datatable"></param> /// <param name="filepath"></param> /// <param name="error"></param> /// <returns></returns> public static bool DataTableToExcel(DataTable datatable, string filepath, out string error) { error = "" ; try { if (datatable == null ) { error = "DataTableToExcel:datatable 为空" ; return false ; } Aspose.Cells.Workbook workbook = new Aspose.Cells.Workbook(); Aspose.Cells.Worksheet sheet = workbook.Worksheets[0]; Aspose.Cells.Cells cells = sheet.Cells; int nRow = 0; foreach (DataRow row in datatable.Rows) { nRow++; try { for ( int i = 0; i < datatable.Columns.Count; i++) { if (row[i].GetType().ToString() == "System.Drawing.Bitmap" ) { //------插入图片数据------- System.Drawing.Image image = (System.Drawing.Image)row[i]; MemoryStream mstream = new MemoryStream(); image.Save(mstream, System.Drawing.Imaging.ImageFormat.Jpeg); sheet.Pictures.Add(nRow, i, mstream); } else { cells[nRow, i].PutValue(row[i]); } } } catch (System.Exception e) { error = error + " DataTableToExcel: " + e.Message; } } workbook.Save(filepath); return true ; } catch (System.Exception e) { error = error + " DataTableToExcel: " + e.Message; return false ; } } /// <summary> /// 工作表转为图片 /// </summary> /// <param name="file">来源EXCEL文件</param> /// <param name="sheetname">工作表名</param> /// <param name="toimagefile">生成图片文件</param> public static void CellConverImge( string file, string sheetname, string toimagefile) { //Create a new Workbook object and //Open a template Excel file. Workbook book = new Workbook(file); //Get the first worksheet. Worksheet sheet = book.Worksheets[sheetname]; //Define ImageOrPrintOptions ImageOrPrintOptions imgOptions = new ImageOrPrintOptions(); //Specify the image format imgOptions.ImageFormat = System.Drawing.Imaging.ImageFormat.Jpeg; //Only one page for the whole sheet would be rendered imgOptions.OnePagePerSheet = true ; //Render the sheet with respect to specified image/print options SheetRender sr = new SheetRender(sheet, imgOptions); //Render the image for the sheet Bitmap bitmap = sr.ToImage(0); //Save the image file specifying its image format. bitmap.Save(toimagefile); } /// <summary> /// /// </summary> /// <param name="sURL"></param> /// <param name="toExcelFile"></param> public static void LoadUrlImage( string sURL, string toExcelFile) { //Define memory stream object System.IO.MemoryStream objImage; //Define web client object System.Net.WebClient objwebClient; //Define a string which will hold the web image url //string sURL = "http://files.myopera.com/Mickeyjoe_irl/albums/38458/abc.jpg"; try { //Instantiate the web client object objwebClient = new System.Net.WebClient(); //Now, extract data into memory stream downloading the image data into the array of bytes objImage = new System.IO.MemoryStream(objwebClient.DownloadData(sURL)); //Create a new workbook Aspose.Cells.Workbook wb = new Aspose.Cells.Workbook(); //Get the first worksheet in the book Aspose.Cells.Worksheet sheet = wb.Worksheets[0]; //Get the first worksheet pictures collection Aspose.Cells.Drawing.PictureCollection pictures = sheet.Pictures; //Insert the picture from the stream to B2 cell pictures.Add(1, 1, objImage); //Save the excel file "d:\\test\\webimagebook.xls" wb.Save(toExcelFile); } catch (Exception ex) { //Write the error message on the console Console.WriteLine(ex.Message); } } /// <summa /// <summary> /// 涂聚文 /// 20150228 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnFile_Click( object sender, EventArgs e) { try { //bool imail = false; this .Cursor = Cursors.WaitCursor; openFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); //JPEG Files (*.jpeg)|*.jpeg|PNG Files (*.png)|*.png|JPG Files (*.jpg)|*.jpg|GIF Files (*.gif)|*.gif openFileDialog1.FileName = "" ; openFileDialog1.Filter = "Excel 2000-2003 files(*.xls)|*.xls|Excel 2007 files (*.xlsx)|*.xlsx" ; //|(*.xlsx)|*.xlsx Image Files(*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|All files (*.*)|*.* txt files (*.txt)|*.txt|All files (*.*)|*.*" openFileDialog1.FilterIndex = 2; openFileDialog1.RestoreDirectory = true ; if (openFileDialog1.ShowDialog() == DialogResult.OK) { if (!openFileDialog1.FileName.Equals(String.Empty)) { //重新加载清除数据 this .combSheet.DataSource = null ; if ( this .combSheet.Items.Count != 0) { this .combSheet.Items.Clear(); } FileInfo f = new FileInfo(openFileDialog1.FileName); if (f.Extension.Equals( ".xls" ) || f.Extension.Equals( ".XLS" ) || f.Extension.Equals( ".xlsx" )) { this .Cursor = Cursors.WaitCursor; strFileUrl = openFileDialog1.SafeFileName; this .txtFileUrl.Text = openFileDialog1.FileName; string currentfilename = openFileDialog1.FileName; this .txtFileUrl.Text = currentfilename; // // ("463588883@qq.com", "geovindu", "金至尊文件", "文件", currentfilename); //MessageBox.Show(imail.ToString()); AsposeExcel.ReadExcelCombox(currentfilename,combSheet); this .Cursor = Cursors.Default; } else { MessageBox.Show( "错添文件类型" ); } } else { MessageBox.Show( "你要选择一下精确位置的文件" ); } } } catch (Exception ex) { ex.Message.ToString(); } this .Cursor = Cursors.Default; } /// <summary> /// 导入 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnImport_Click( object sender, EventArgs e) { DataTable dt = new DataTable(); //默认第一行为标题 dt= AsposeExcel.ReadExcel( this .txtFileUrl.Text.Trim(), this .combSheet.Text.Trim()); this .dataGridView1.DataSource = dt; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | /// <summary> /// /// </summary> public partial class _Default : System.Web.UI.Page { DataTable getData() { DataTable dt = new DataTable(); dt.Columns.Add( "id" , typeof ( int )); dt.Columns.Add( "name" , typeof ( string )); dt.Rows.Add(1, "geovindu" ); dt.Rows.Add(2, "geov" ); return dt; } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void Page_Load( object sender, EventArgs e) { if (!IsPostBack) { this .GridView1.DataSource = getData(); this .GridView1.DataBind(); } } /// <summary> /// /// </summary> /// <param name="dataTable"></param> /// <param name="fileName"></param> protected void ExportToExcel(DataTable dataTable, string fileName) { HttpContext context = HttpContext.Current; context.Response.Clear(); foreach (DataColumn column in dataTable.Columns) { context.Response.Write(column.ColumnName + "," ); } context.Response.Write(Environment.NewLine); foreach (DataRow row in dataTable.Rows) { for ( int i = 0; i < dataTable.Columns.Count; i++) { context.Response.Write(row[i].ToString() + "," ); } context.Response.Write(Environment.NewLine); } context.Response.ContentType = "application / ms - excel" ; context.Response.AppendHeader( "Content-Disposition" , "attachment; filename=" + fileName + ".csv" ); context.Response.End(); } protected void Button1_Click( object sender, EventArgs e) { ExportToExcel(getData(), "toni" ); } |
哲学管理(学)人生, 文学艺术生活, 自动(计算机学)物理(学)工作, 生物(学)化学逆境, 历史(学)测绘(学)时间, 经济(学)数学金钱(理财), 心理(学)医学情绪, 诗词美容情感, 美学建筑(学)家园, 解构建构(分析)整合学习, 智商情商(IQ、EQ)运筹(学)生存.---Geovin Du(涂聚文)
分类:
CSharp code
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
2006-02-28 C#正则表达式实例