C# 操作Excel代碼總結(jié)
本文分享了c#操作Excel的相關(guān)代碼,還是比較全面的,其實(shí)無外乎存取,增刪改查等操作,參考下。
具體代碼:
//引用Microsoft.Office.Interop.Excel.dll文件
//添加using
using Microsoft.Office.Interop.Excel;
using Excel=Microsoft.Office.Interop.Excel;
//設(shè)置程序運(yùn)行語言
System.Globalization.CultureInfo CurrentCI = System.Threading.Thread.CurrentThread.CurrentCulture;
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
//創(chuàng)建Application
Excel.Application xlApp = new Excel.Application();
//設(shè)置是否顯示警告窗體
excelApp.DisplayAlerts = false;
//設(shè)置是否顯示Excel
excelApp.Visible = false;
//禁止刷新屏幕
excelApp.ScreenUpdating = false;
//根據(jù)路徑path打開
Excel.Workbook xlsWorkBook = excelApp.Workbooks.Open(path, System.Type.Missing, System.Type.Missing, System.Type.Missing,
System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing,
System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing);
//獲取Worksheet對(duì)象
Excel.Worksheet xlsWorkSheet = (Worksheet)xlsWorkBook.Worksheets["sales plan"];
***獲取最后一行、一列的兩種方法***
//獲取已用的范圍數(shù)據(jù)
int rowsCount = xlsWorkSheet.UsedRange.Rows.Count;
int colsCount = xlsWorkSheet.UsedRange.Columns.Count;
int rowsCount = xlsWorkSheet.get_Range("A65536", "A65536").get_End(Microsoft.Office.Interop.Excel.XlDirection.xlUp).Row;
int colsCount = xlsWorkSheet.get_Range("ZZ1", "ZZ1").get_End(Microsoft.Office.Interop.Excel.XlDirection.xlToLeft).Column;
***將Excel數(shù)據(jù)存入二維數(shù)組***
//rowsCount:最大行 colsCount:最大列
Microsoft.Office.Interop.Excel.Range c1 = (Microsoft.Office.Interop.Excel.Range)xlsWorkSheet.Cells[1, 1];
Microsoft.Office.Interop.Excel.Range c2 = (Microsoft.Office.Interop.Excel.Range)xlsWorkSheet.Cells[rowsCount, colsCount];
Range rng = (Microsoft.Office.Interop.Excel.Range)xlsWorkSheet.get_Range(c1, c2);
object[,] exceldata = (object[,])rng.get_Value(Microsoft.Office.Interop.Excel.XlRangeValueDataType.xlRangeValueDefault);
//在第一列的左邊插入一列
Excel.Range xlsColumns = (Excel.Range)xlsWorkSheet.Columns[1, System.Type.Missing];
xlsColumns.Insert(XlInsertShiftDirection.xlShiftToRight, Type.Missing);
//xlsSheetTemplateMajor_Meisai.Cells.get_Range(xlsSheetTemplateMajor_Meisai.Cells[1, 1], xlsSheetTemplateMajor_Meisai.Cells[65535, 1]).Insert(Type.Missing, Type.Missing);
Excel.Range rng;
rng = worksheet.get_Range("A:A", "A:A");
rng.Insert(Excel.XlDirection.xlToRight, Excel.XlInsertFormatOrigin.xlFormatFromLeftOrAbove);
Excel.Range rng = (Microsoft.Office.Interop.Excel.Range)xlsWorkSheet.Columns[12, Type.Missing];
rng.Insert(XlInsertShiftDirection.xlShiftToRight, XlInsertFormatOrigin.xlFormatFromLeftOrAbove);
//刪除行
Range deleteRng = (Range)xlsWorkSheetSapExcel.Rows[2, System.Type.Missing];
deleteRng.Delete(Excel.XlDeleteShiftDirection.xlShiftUp);
//刪除一列數(shù)據(jù)
((Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[1, 11]).Select();
((Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[1, 11]).EntireColumn.Delete(0);
((Excel.Range)xlsSheetShareMajor_Meisai.Cells[1, 3]).EntireColumn.Delete (0);
//設(shè)置背景色為紅色
xlsWorkSheet.get_Range("A1", "A1").Interior.ColorIndex = 3;
//設(shè)置Format屬性 屬性值可以通過在vba中錄宏得到
Microsoft.Office.Interop.Excel.Range range1 = xlsWorkSheetAdd.get_Range("J1", "J65535");
range1.NumberFormat = "@";//文本格式
range1 = xlsWorkSheetAdd.get_Range("L1", "L65535");
range1.NumberFormat = "0.00";//保留兩位小數(shù)
Excel.Range rng = xlsSheetShareMajor_Meisai.Columns["I", System.Type.Missing] as Excel.Range;
rng.NumberFormatLocal =@"yyyy/m/d";//設(shè)置日期格式
//替換
Range Drng = xlsWorkSheetTemplate.get_Range("D1", "D65535");
Drng.Replace(" ", "", XlLookAt.xlPart, XlSearchOrder.xlByColumns, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing);
Drng.TextToColumns(Drng, Excel.XlTextParsingType.xlDelimited, Excel.XlTextQualifier.xlTextQualifierSingleQuote, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing);
//分列處理 設(shè)置為文本
Range TextToColumnRng = xlsWorkSheet.get_Range("E1", "E65535");
xlsWorkSheet.get_Range("E1", "E65535").TextToColumns(TextToColumnRng, Excel.XlTextParsingType.xlDelimited, Excel.XlTextQualifier.xlTextQualifierSingleQuote, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing);
//設(shè)置公式
rng = xlMergeFileWorkSheet.get_Range("D2", "D" + rowcount);//設(shè)置列范圍
rng.Formula = @"=IF(RC[-3]=""H"",""Survivor"",""Donor"")";//設(shè)置公式 @的問題
//rng.NumberFormat = "$0.00";//設(shè)置格式
copyRng = xlsSheetTemplateMajor_Meisai.get_Range("N3", "N" + lastRowTemplate);
copyRng.Formula = "=VLOOKUP(RC[-12],AR殘!C[-13]:C[-11],2,0)";
//通過行、列的索引獲取值
string f = Convert.ToString(xlsSheetShareMajor_Meisai.get_Range(xlsSheetShareMajor_Meisai.Cells[2, 1], xlsSheetShareMajor_Meisai.Cells[2,1]).Value2);
//篩選
//確定篩選范圍
D1_rng = D1_TemSheet.Cells.get_Range(D1_TemSheet.Cells[1, 1], D1_TemSheet.Cells[1, 50]);
//執(zhí)行篩選動(dòng)作
rng.AutoFilter(5, "S", Microsoft.Office.Interop.Excel.XlAutoFilterOperator.xlFilterValues, Type.Missing, true);
rng.AutoFilter(6, "H", Microsoft.Office.Interop.Excel.XlAutoFilterOperator.xlOr, "F", true);
D1_rng.AutoFilter(D1_Column + 2, "#N/A", Microsoft.Office.Interop.Excel.XlAutoFilterOperator.xlFilterValues,"#N/A",false);
//復(fù)制粘貼
D2_rng.Copy(Type.Missing);
D2_TemSheet.Cells.get_Range(D2_TemSheet.Cells[2, (D2_Column + 1)], D2_TemSheet.Cells[2, (D2_Column + 1)]).PasteSpecial(Excel.XlPasteType.xlPasteValues, Excel.XlPasteSpecialOperation.xlPasteSpecialOperationNone, false, false);
//Find查找
rng = mySheet.get_Range("A1", "IV10").Find(arrLabel[j], Type.Missing,
Microsoft.Office.Interop.Excel.XlFindLookIn.xlValues, Microsoft.Office.Interop.Excel.XlLookAt.xlWhole,
Microsoft.Office.Interop.Excel.XlSearchOrder.xlByRows,
Microsoft.Office.Interop.Excel.XlSearchDirection.xlNext, false, Type.Missing, Type.Missing);
//文字占滿單元格
range.EntireColumn.AutoFit();
//另存
xlsWorkBook.SaveAs(FileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
***關(guān)閉對(duì)象***
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlsWorkSheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlsWorkBook);
excelApp.Quit();
Kill(excelApp);//調(diào)用方法關(guān)閉進(jìn)程
GC.Collect();
/// <summary>
/// 關(guān)閉Excel進(jìn)程
/// </summary>
public class KeyMyExcelProcess
{
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int ID);
public static void Kill(Microsoft.Office.Interop.Excel.Application excel)
{
try
{
IntPtr t = new IntPtr(excel.Hwnd); //得到這個(gè)句柄,具體作用是得到這塊內(nèi)存入口
int k = 0;
GetWindowThreadProcessId(t, out k); //得到本進(jìn)程唯一標(biāo)志k
System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById(k); //得到對(duì)進(jìn)程k的引用
p.Kill(); //關(guān)閉進(jìn)程k
}
catch (System.Exception ex)
{
throw ex;
}
}
}
//關(guān)閉打開的Excel方法
public void CloseExcel(Microsoft.Office.Interop.Excel.Application ExcelApplication, Microsoft.Office.Interop.Excel.Workbook ExcelWorkbook)
{
ExcelWorkbook.Close(false, Type.Missing, Type.Missing);
ExcelWorkbook = null;
ExcelApplication.Quit();
GC.Collect();
KeyMyExcelProcess.Kill(ExcelApplication);
}
總結(jié)
以上就是本文關(guān)于C# 操作Excel代碼總結(jié)的全部內(nèi)容,希望對(duì)大家有所幫助。感興趣的朋友可以繼續(xù)參閱本站其他相關(guān)專題,如有不足之處,歡迎留言指出。感謝朋友們對(duì)本站的支持!
相關(guān)文章
C#獲取鼠標(biāo)在listview右鍵點(diǎn)擊單元格的內(nèi)容方法
下面小編就為大家?guī)硪黄狢#獲取鼠標(biāo)在listview右鍵點(diǎn)擊單元格的內(nèi)容方法。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-01-01
C#上位機(jī)與三菱PLC通訊的實(shí)現(xiàn)步驟(圖文)
這篇文章主要介紹了C#上位機(jī)與三菱PLC通訊的實(shí)現(xiàn)步驟(圖文),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-02-02
unity實(shí)現(xiàn)按住鼠標(biāo)選取區(qū)域截圖
這篇文章主要為大家詳細(xì)介紹了unity實(shí)現(xiàn)按住鼠標(biāo)選取區(qū)域截圖,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-04-04
C#學(xué)習(xí)筆記- 淺談數(shù)組復(fù)制,排序,取段,元組
下面小編就為大家?guī)硪黄狢#學(xué)習(xí)筆記- 淺談數(shù)組復(fù)制,排序,取段,元組。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2016-08-08
c# Invoke和BeginInvoke 區(qū)別分析
這篇文章主要介紹了c# Invoke和BeginInvoke 區(qū)別分析,需要的朋友可以參考下2014-10-10
c#中SAPI使用總結(jié)——SpVoice的使用方法
最近使用C#重做了點(diǎn)名系統(tǒng)(要用到TTS,讓計(jì)算機(jī)點(diǎn)名)使用了SAPI,在這里總結(jié)一下SpVoice的使用方法。2011-10-10
IIS下調(diào)用證書出現(xiàn)異常的解決方法 (C#)
這篇文章主要為大家詳細(xì)介紹了IIS下調(diào)用證書出現(xiàn)異常的解決方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-05-05

