编程调试时,如果能够及时的将数据输出分析,可以更快的发现问题和解决问题。
添加引用:Microsoft.Office.Interop.Excel
读出数据:
Microsoft.Office.Interop.Excel.application excel = new Microsoft.Office.Interop.Excel.Application(); Microsoft.Office.Interop.Excel.Workbook xlBook = excel.Workbooks.Add(true); Microsoft.Office.Interop.Excel.Worksheet xlSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlBook.Worksheets[1]; int rows = Def.array1.Count;//行,data为二维数组 int cols = Def.array1[0].Count;//列,data为二维数组 for (int m = 0; m < rows; m++) { for (int n = 0; n < cols; n++) { excel.Cells[m + 1, n + 1] = Def.array1.ElementAt(m).ElementAt(n).ToString();//写入数据 } } xlBook.Saved = true; xlBook.SaveCopyAs(@"G:/MyPRoject/BipVDeviceOptiAutoDeploy/BIPVDeviceOptiAutoDeploy/RadiationData.xls"); excel.Quit(); excel = null; GC.Collect();
单张sheet
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application(); Microsoft.Office.Interop.Excel.Workbook xlBook = excel.Workbooks.Add(true);//Excel工作簿对象 Microsoft.Office.Interop.Excel.Sheets sheets = xlBook.Sheets;//获取所有表单 for (int k = 0; k < ds1.Tables.Count; k++) { Microsoft.Office.Interop.Excel.Worksheet worksheet = sheets.get_Item(k+1);//获取指定的sheet表 System.Data.DataTable dt = ds1.Tables[k]; int row = dt.Rows.Count;//第k个表的行数 int col = dt.Columns.Count;
//向指定的表单进行数据插入 for (int m = 0; m < row; m++) { for (int n = 0; n < col; n++) { excel.Cells[m + 1, n + 1] = dt.Rows[m][n].ToString();//写入数据 } } if(k == ds1.Tables.Count - 1) { continue;//不生成数据表单 } else { Microsoft.Office.Interop.Excel.Worksheet xlSheet = sheets.Add(Missing.Value, Missing.Value, Missing.Value, Missing.Value);//每次创建一个表单存入数据 }
} xlBook.Saved = true; xlBook.SaveCopyAs(@"./DataTable.xls");
excel.Quit(); excel = null; GC.Collect();
多张sheet表
读入数据:存入二维数组(Excel一个sheet表)
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using aspose.Cells;namespace ExcelRead{ class Program { //////////////////////////////////// public List<List<double>> GetImportExcelRoute(Workbook excel) { int icount = excel.Worksheets.Count;
List<List<double>> routList = new List<List<double>>(); for (int i = 0; i < icount; i++) { Worksheet sheet = excel.Worksheets[i]; Cells cells = sheet.Cells; int rowcount = cells.MaxDataRow; int columncount = cells.MaxDataColumn; if (rowcount > 0 && columncount > 0) { for (int row = 0; row <= rowcount; row++ ) { List<double> rowValue = new List<double>(); for (int col = 0; col <= columncount; col++) { double value = cells[row, col].DoubleValue; rowValue.Insert(col, value); } routList.Add(rowValue) ; } } } return routList; } /////////////////////////////////////
private void Import() { string excelName = "D://test.xls"; Workbook excel = new Workbook(excelName); List<List<double>> importyString = GetImportExcelRoute(excel); } static void Main(string[] args) { Program a = new Program(); a.Import(); } }}
新闻热点
疑难解答