本篇文章主要介紹了C#實現幾十萬級資料匯出Excel及Excel各種操作執行個體,這裡整理了詳細的代碼,有需要的小夥伴可以參考下。
先上匯出代碼
/// <summary> /// 匯出速度最快 /// </summary> /// <param name="list"><列名,資料></param> /// <param name="filepath"></param> /// <returns></returns> public bool NewExport(List<DictionaryEntry> list, string filepath) { bool bSuccess = true; Microsoft.Office.Interop.Excel.Application appexcel = new Microsoft.Office.Interop.Excel.Application(); System.Reflection.Missing miss = System.Reflection.Missing.Value; appexcel = new Microsoft.Office.Interop.Excel.Application(); Microsoft.Office.Interop.Excel.Workbook workbookdata = null; Microsoft.Office.Interop.Excel.Worksheet worksheetdata = null; Microsoft.Office.Interop.Excel.Range rangedata; workbookdata = appexcel.Workbooks.Add(); //設定對象不可見 appexcel.Visible = false; appexcel.DisplayAlerts = false; try { foreach (var lv in list) { var keys = lv.Key as List<string>; var values = lv.Value as List<IList<object>>; worksheetdata = (Microsoft.Office.Interop.Excel.Worksheet)workbookdata.Worksheets.Add(miss, workbookdata.ActiveSheet); for (int i = 0; i < keys.Count-1; i++) { //給工作表賦名稱 worksheetdata.Name = keys[0];//列名的第一個資料位元表名 worksheetdata.Cells[1, i + 1] = keys[i+1]; } //因為第一行已經寫了表頭,所以所有資料都應該從a2開始 rangedata = worksheetdata.get_Range("a2", miss); Microsoft.Office.Interop.Excel.Range xlrang = null; //irowcount為實際行數,最大行 int irowcount = values.Count; int iparstedrow = 0, icurrsize = 0; //ieachsize為每次寫行的數值,可以自己設定 int ieachsize = 10000; //icolumnaccount為實際列數,最大列數 int icolumnaccount = keys.Count-1; //在記憶體中聲明一個ieachsize×icolumnaccount的數組,ieachsize是每次最大儲存的行數,icolumnaccount就是儲存的實際列數 object[,] objval = new object[ieachsize, icolumnaccount]; icurrsize = ieachsize; while (iparstedrow < irowcount) { if ((irowcount - iparstedrow) < ieachsize) icurrsize = irowcount - iparstedrow; //用for迴圈給數組賦值 for (int i = 0; i < icurrsize; i++) { for (int j = 0; j < icolumnaccount; j++) { var v = values[i + iparstedrow][j]; objval[i, j] = v != null ? v.ToString() : ""; } } string X = "A" + ((int)(iparstedrow + 2)).ToString(); string col = ""; if (icolumnaccount <= 26) { col = ((char)('A' + icolumnaccount - 1)).ToString() + ((int)(iparstedrow + icurrsize + 1)).ToString(); } else { col = ((char)('A' + (icolumnaccount / 26 - 1))).ToString() + ((char)('A' + (icolumnaccount % 26 - 1))). ToString() + ((int)(iparstedrow + icurrsize + 1)).ToString(); } xlrang = worksheetdata.get_Range(X, col); xlrang.NumberFormat = "@"; // 調用range的value2屬性,把記憶體中的值賦給excel xlrang.Value2 = objval; iparstedrow = iparstedrow + icurrsize; } } ((Microsoft.Office.Interop.Excel.Worksheet)workbookdata.Worksheets["Sheet1"]).Delete(); ((Microsoft.Office.Interop.Excel.Worksheet)workbookdata.Worksheets["Sheet2"]).Delete(); ((Microsoft.Office.Interop.Excel.Worksheet)workbookdata.Worksheets["Sheet3"]).Delete(); //儲存工作表 workbookdata.SaveAs(filepath, miss, miss, miss, miss, miss, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, miss, miss, miss); workbookdata.Close(false, miss, miss); appexcel.Workbooks.Close(); appexcel.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(workbookdata); System.Runtime.InteropServices.Marshal.ReleaseComObject(appexcel.Workbooks); System.Runtime.InteropServices.Marshal.ReleaseComObject(appexcel); GC.Collect(); } catch (Exception ex) { ErrorMsg = ex.Message; bSuccess = false; } finally { if (appexcel != null) { ExcelImportHelper.KillSpecialExcel(appexcel); } } return bSuccess; }
range.NumberFormatLocal = "@"; //設定儲存格格式為文本 range = (Range)worksheet.get_Range("A1", "E1"); //擷取Excel多個儲存格範圍:本例做為Excel表頭 range.Merge(0); //儲存格合并動作 worksheet.Cells[1, 1] = "Excel儲存格賦值"; //Excel儲存格賦值 range.Font.Size = 15; //設定字型大小 range.Font.Underline=true; //設定字型是否有底線 range.Font.Name="黑體"; 設定字型的種類 range.HorizontalAlignment=XlHAlign.xlHAlignCenter; //設定字型在儲存格內的對其方式 range.ColumnWidth=15; //設定儲存格的寬度 range.Cells.Interior.Color=System.Drawing.Color.FromArgb(255,204,153).ToArgb(); //設定儲存格的背景色 range.Borders.LineStyle=1; //設定儲存格邊框的粗細 range.BorderAround(XlLineStyle.xlContinuous,XlBorderWeight.xlThick,XlColorIndex.xlColorIndexAutomatic,System.Drawing.Color.Black.ToArgb()); //給儲存格加邊框 range.Borders.get_Item(Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeTop).LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlLineStyleNone; //設定儲存格上邊框為無邊框 range.EntireColumn.AutoFit(); //自動調整列寬 Range.HorizontalAlignment= xlCenter; // 文本水平置中方式 Range.VerticalAlignment= xlCenter //文本垂直置中方式 Range.WrapText=true; //文本自動換行 Range.Interior.ColorIndex=39; //填充顏色為淡紫色 Range.Font.Color=clBlue; //字型顏色 xlsApp.DisplayAlerts=false; //對Excel的操作 不彈出提示資訊 ApplicationClass xlsApp = new ApplicationClass(); // 1. 建立Excel應用程式物件的一個執行個體,相當於我們從開始菜單開啟Excel應用程式。 if (xlsApp == null) { //對此執行個體進行驗證,如果為null則表示運行此代碼的機器可能未安裝Excel }
1. 開啟現有的Excel檔案
Workbook workbook = xlsApp.Workbooks.Open(excelFilePath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); Worksheet mySheet = workbook.Sheets[1] as Worksheet; //第一個sheet頁 mySheet.Name = "testsheet"; //這裡修改sheet名稱
2.複製sheet頁
mySheet.Copy(Type.Missing, workbook.Sheets[1]);//複製mySheet成一個新的sheet頁,複製完後的名稱是mySheet頁名稱後加一個(2),這裡就是testsheet(2),複製完後,Worksheet的數量增加一個
注意 這裡Copy方法的兩個參數,指是的複製出來新的sheet頁是在指定sheet頁的前面還是後面,上面的例子就是指複製的sheet頁在第一個sheet頁的後面。
3.刪除sheet頁
xlsApp.DisplayAlerts = false; //如果想刪除某個sheet頁,首先要將此項設為fasle。 (xlsApp.ActiveWorkbook.Sheets[1] as Worksheet).Delete();
4.選中sheet頁
複製代碼 代碼如下:
(xlsApp.ActiveWorkbook.Sheets[1] as Worksheet).Select(Type.Missing); //選中某個sheet頁
5.另存excel檔案
workbook.Saved = true; workbook.SaveCopyAs(filepath);
6.釋放excel資源
workbook.Close(true, Type.Missing, Type.Missing); workbook = null; xlsApp.Quit(); xlsApp = null;
方法2:
using System;using System.Collections.Generic;using System.Linq;using System.Text;using Microsoft.Office.Interop.Excel;using System.Data;namespace ExcelTest{ public class ExcelUtil { System.Data.DataTable table11 = new System.Data.DataTable(); public void ExportToExcel(System.Data.DataTable table, string saveFileName) { bool fileSaved = false; //ExcelApp xlApp = new ExcelApp(); Application xlApp = new Application(); if (xlApp == null) { return; } Workbooks workbooks = xlApp.Workbooks; Workbook workbook = workbooks.Add(XlWBATemplate.xlWBATWorksheet); Worksheet worksheet = (Worksheet)workbook.Worksheets[1];//取得sheet1 long rows = table.Rows.Count; /*下邊注釋的兩行代碼當資料行數超過行時,出現異常:異常來自HRESULT:0x800A03EC。因為:Excel 2003每個sheet只支援最大行資料 //Range fchR = worksheet.get_Range(worksheet.Cells[1, 1], worksheet.Cells[table.Rows.Count+2, gridview.Columns.View.VisibleColumns.Count+1]); //fchR.Value2 = datas;*/ if (rows > 65535) { long pageRows = 60000;//定義每頁顯示的行數,行數必須小於 int scount = (int)(rows / pageRows); if (scount * pageRows < table.Rows.Count)//當總行數不被pageRows整除時,經過四捨五入可能頁數不準 { scount = scount + 1; } for (int sc = 1; sc <= scount; sc++) { if (sc > 1) { object missing = System.Reflection.Missing.Value; worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets.Add( missing, missing, missing, missing);//添加一個sheet } else { worksheet = (Worksheet)workbook.Worksheets[sc];//取得sheet1 } string[,] datas = new string[pageRows + 1, table.Columns.Count+ 1];for (int i = 0; i < table.Columns.Count; i++) //寫入欄位 { datas[0, i] = table.Columns[i].Caption; } Range range = worksheet.get_Range(worksheet.Cells[1, 1], worksheet.Cells[1, table.Columns.Count]); range.Interior.ColorIndex = 15;//15代表灰色 range.Font.Bold = true; range.Font.Size = 9; int init = int.Parse(((sc - 1) * pageRows).ToString()); int r = 0; int index = 0; int result; if (pageRows * sc >= table.Rows.Count) { result = table.Rows.Count; } else { result = int.Parse((pageRows * sc).ToString()); } for (r = init; r < result; r++) { index = index + 1; for (int i = 0; i < table.Columns.Count; i++) { if (table.Columns[i].DataType == typeof(string) || table.Columns[i].DataType == typeof(Decimal) || table.Columns[i].DataType == typeof(DateTime)) { object obj = table.Rows[r][table.Columns[i].ColumnName]; datas[index, i] = obj == null ? "" : "'" + obj.ToString().Trim();//在obj.ToString()前加單引號是為了防止自動轉化格式 } } } Range fchR = worksheet.get_Range(worksheet.Cells[1, 1], worksheet.Cells[index + 2, table.Columns.Count + 1]); fchR.Value2 = datas; worksheet.Columns.EntireColumn.AutoFit();//列寬自適應。 range = worksheet.get_Range(worksheet.Cells[1, 1], worksheet.Cells[index + 1, table.Columns.Count]); //15代表灰色 range.Font.Size = 9; range.RowHeight = 14.25; range.Borders.LineStyle = 1; range.HorizontalAlignment = 1; } } else { string[,] datas = new string[table.Rows.Count + 2, table.Columns.Count + 1]; for (int i = 0; i < table.Columns.Count; i++) //寫入欄位 { datas[0, i] = table.Columns[i].Caption; } Range range = worksheet.get_Range(worksheet.Cells[1, 1], worksheet.Cells[1, table.Columns.Count]); range.Interior.ColorIndex = 15;//15代表灰色 range.Font.Bold = true; range.Font.Size = 9; int r = 0; for (r = 0; r < table.Rows.Count; r++) { for (int i = 0; i < table.Columns.Count; i++) { if (table.Columns[i].DataType == typeof(string) || table.Columns[i].DataType == typeof(Decimal) || table.Columns[i].DataType == typeof(DateTime)) { object obj = table.Rows[r][table.Columns[i].ColumnName]; datas[r + 1, i] = obj == null ? "" : "'" + obj.ToString().Trim();//在obj.ToString()前加單引號是為了防止自動轉化格式 } } //System.Windows.Forms.Application.DoEvents();} Range fchR = worksheet.get_Range(worksheet.Cells[1, 1], worksheet.Cells[table.Rows.Count + 2, table.Columns.Count + 1]); fchR.Value2 = datas; worksheet.Columns.EntireColumn.AutoFit();//列寬自適應。 range = worksheet.get_Range(worksheet.Cells[1, 1], worksheet.Cells[table.Rows.Count + 1, table.Columns.Count]); //15代表灰色 range.Font.Size = 9; range.RowHeight = 14.25; range.Borders.LineStyle = 1; range.HorizontalAlignment = 1; } if (saveFileName != "") { try { workbook.Saved = true; workbook.SaveCopyAs(saveFileName); fileSaved = true; } catch (Exception ex) { fileSaved = false; } } else { fileSaved = false; } xlApp.Quit(); GC.Collect();//強行銷毀 } }}
方法3:
先去官網:http://www.php.cn/下載需要引入dll(可以選擇.net2.0或者.net4.0的dll),然後在網站中添加引用。
匯出代碼:
NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();NPOI.SS.UserModel.ISheet sheet = book.CreateSheet("test_01");// 第一列NPOI.SS.UserModel.IRow row = sheet.CreateRow(0);row.CreateCell(0).SetCellValue("第一列第一行");// 第二列NPOI.SS.UserModel.IRow row2 = sheet.CreateRow(1);row2.CreateCell(0).SetCellValue("第二列第一行");// ...// 寫入到用戶端 System.IO.MemoryStream ms = new System.IO.MemoryStream();book.Write(ms);Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xls", DateTime.Now.ToString("yyyyMMddHHmmssfff")));Response.BinaryWrite(ms.ToArray());book = null;ms.Close();ms.Dispose();
匯入代碼:
HSSFWorkbook hssfworkbook; #region public DataTable ImportExcelFile(string filePath) { #region//初始化資訊 try { using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read)) { hssfworkbook = new HSSFWorkbook(file); } } catch (Exception e) { throw e; } #endregion NPOI.SS.UserModel.Sheet sheet = hssfworkbook.GetSheetAt(0); System.Collections.IEnumerator rows = sheet.GetRowEnumerator(); DataTable dt = new DataTable(); for (int j = 0; j < (sheet.GetRow(0).LastCellNum); j++) { dt.Columns.Add(Convert.ToChar(((int)'A') + j).ToString()); } while (rows.MoveNext()) { HSSFRow row = (HSSFRow)rows.Current; DataRow dr = dt.NewRow(); for (int i = 0; i < row.LastCellNum; i++) { NPOI.SS.UserModel.Cell cell = row.GetCell(i); if (cell == null) { dr[i] = null; } else { dr[i] = cell.ToString(); } } dt.Rows.Add(dr); } return dt; } #endregion
用法:
首先建立一個空白的活頁簿用作測試,並在其中建立空白工作表,在表中建立空白行,在行中建立儲存格,並填入內容:
//建立空白活頁簿IWorkbook workbook = new HSSFWorkbook();//在活頁簿中:建立空白工作表ISheet sheet = workbook.CreateSheet();//在工作表中:建立行,參數為行號,從0計IRow row = sheet.CreateRow(0);//在行中:建立儲存格,參數為列號,從0計ICell cell = row.CreateCell(0);//設定儲存格內容cell.SetCellValue("實習評鑑表");
設定儲存格樣式:設定儲存格樣式時需要注意,務必建立一個新的樣式對象進行設定,否則會將工作表所有儲存格的樣式一同設定,它們應該共用的是一個樣式對象:
ICellStyle style = workbook.CreateCellStyle();//設定儲存格的樣式:水平對齊置中style.Alignment = HorizontalAlignment.CENTER;//建立一個字型樣式對象IFont font = workbook.CreateFont();//設定字型加粗樣式font.Boldweight = short.MaxValue;//使用SetFont方法將字型樣式添加到儲存格樣式中 style.SetFont(font);//將新的樣式賦給儲存格cell.CellStyle = style;
設定儲存格寬高:
設定儲存格的高度實際是設定其所在行高,所以要在儲存格所在行上設定行高,行高設定數值好像是像素點的1/20,所以*20以便達到設定效果;
設定儲存格的寬度實際上是設定其所在列寬,所以要在儲存格所在列上設定(列的設定在工作表上),寬度數值好像是字元的1/256,所以*256以便達到設定效果。
//設定儲存格的高度row.Height = 30 * 20;//設定儲存格的寬度sheet.SetColumnWidth(0, 30 * 256);
合併儲存格:合併儲存格實際上是聲明一個地區,該地區中的儲存格將進行合并,合并後的內容與樣式以該地區最左上方的儲存格為準。
//設定一個合併儲存格地區,使用上下左右定義CellRangeAddress地區//CellRangeAddress四個參數為:起始行,結束行,起始列,結束列sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, 10));
添加公式:使用Cell的CellFormula來設定公式,是一個字串,公式前不需要加=號。
//通過Cell的CellFormula向儲存格中寫入公式//註:直接寫公式內容即可,不需要在最前加'='ICell cell2 = sheet.CreateRow(1).CreateCell(0);cell2.CellFormula = "HYPERLINK(\"測試圖片.jpg\",\"測試圖片.jpg\")";
將活頁簿寫入檔案查看效果:
//將活頁簿寫入檔案using (FileStream fs = new FileStream("產生效果.xls", FileMode.Create, FileAccess.Write)){ workbook.Write(fs);}
以上就是C#實現幾十萬級資料匯出Excel及Excel各種操作執行個體代碼詳解的內容,更多相關內容請關注topic.alibabacloud.com(www.php.cn)!