Skip to content

Instantly share code, notes, and snippets.

@fuwac
Created May 19, 2017 00:23
Show Gist options
  • Save fuwac/2c066212fc750ddffe5e9236663b9946 to your computer and use it in GitHub Desktop.
Save fuwac/2c066212fc750ddffe5e9236663b9946 to your computer and use it in GitHub Desktop.
Excel操作するやつ
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using Excel = Microsoft.Office.Interop.Excel;
namespace excel_proc
{
public partial class Form1 : Form
{
/// <summary>
/// コンストラクタ
/// </summary>
public Form1()
{
InitializeComponent();
// Excel編集テスト
try
{
this.ExcelProc(@"C:\Users\ore\Desktop\test.xlsx");
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
/// <summary>
/// Excelプロセス絶対殺すマン
/// </summary>
private void KillExcelProcess()
{
System.Diagnostics.Process[] procs = System.Diagnostics.Process.GetProcessesByName("Excel");
foreach (System.Diagnostics.Process proc in procs)
{
proc.Kill();
}
}
/// <summary>
/// テキトーに解放処理
/// COMオブジェクトの解放とか、Excel絶対殺すマンとか。
/// </summary>
/// <param name="wb"></param>
/// <param name="app"></param>
private void Release(Excel.Workbook wb, Excel.Application app)
{
// ブック解放
if (wb != null)
{
wb.Close();
}
// Excelアプリ終了
if (app != null)
{
app.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
}
// Excelプロセス強制終了(ゾンビ化問題対策)
this.KillExcelProcess();
}
/// <summary>
/// シート取得処理
/// </summary>
/// <param name="sheetName">取得したいシート名称</param>
/// <param name="work_book">取得対象のワークブック</param>
/// <returns>取得に成功すればワークシートオブジェクト、失敗すればnull</returns>
private Excel.Worksheet GetSheetIndex(string sheetName, Excel.Workbook work_book)
{
foreach (Excel.Worksheet sh in work_book.Sheets)
{
// なんとなく正規表現で部分一致してればOK
if (Regex.IsMatch(sh.Name, sheetName))
{
return sh;
}
}
return null;
}
/// <summary>
/// 指定セルの文字列を取得
/// </summary>
/// <param name="ws">ワークシート</param>
/// <param name="row">セル行</param>
/// <param name="col">セル列</param>
/// <returns>セル内文字列</returns>
private string GetCellString(Excel.Worksheet ws, int row, int col)
{
Excel.Range param;
param = (Excel.Range)ws.Cells[row, col];
return param.Text.ToString();
}
/// <summary>
/// 指定セルに文字列を設定
/// </summary>
/// <param name="ws">ワークシート</param>
/// <param name="row">セル行</param>
/// <param name="col">セル列</param>
/// <param name="value">セル内文字列</param>
private void SetCellString(Excel.Worksheet ws, int row, int col, string value)
{
ws.Cells[row, col].Value = value;
}
/// <summary>
/// セルの内容をコピー
/// </summary>
/// <param name="ws">ワークシート</param>
/// <param name="x1">始点列</param>
/// <param name="y1">始点行</param>
/// <param name="x2">終点列</param>
/// <param name="y2">終点行</param>
private void CellCopy(Excel.Worksheet ws, int x1, int y1, int x2, int y2)
{
ws.Range[ws.Cells[y1, x1], ws.Cells[y2, x2]].Copy();
}
/// <summary>
/// セルの内容を貼り付け
/// </summary>
/// <param name="ws">ワークシート</param>
/// <param name="x1">始点列</param>
/// <param name="y1">始点行</param>
/// <param name="x2">終点列</param>
/// <param name="y2">終点行</param>
private void CellPaste(Excel.Worksheet ws, int x1, int y1, int x2, int y2)
{
ws.Range[ws.Cells[y1, x1], ws.Cells[y2, x2]].PasteSpecial();
}
/// <summary>
/// セルのクリア(範囲)
/// </summary>
/// <param name="ws">ワークシート</param>
/// <param name="x1">始点列</param>
/// <param name="y1">始点行</param>
/// <param name="x2">終点列</param>
/// <param name="y2">終点行</param>
private void CellClear(Excel.Worksheet ws, int x1, int y1, int x2, int y2)
{
ws.Range[ws.Cells[y1, x1], ws.Cells[y2, x2]].Clear();
}
/// <summary>
/// Excel関係の処理いろいろ。書けるだけ書いたので縦長いよ!
/// </summary>
/// <param name="excel_path">Excelファイルのパス</param>
public void ExcelProc(string excel_path)
{
Excel.Application xls_app = null; // Excel用
Excel.Workbook work_book = null; // ブック
Excel.Worksheet work_sheet = null; // シート
try
{
// 既に起動してるExcel居たら怒って処理やめる(最後にExcel絶対殺すマンが居るので)
System.Diagnostics.Process[] procs = System.Diagnostics.Process.GetProcessesByName("Excel");
if (procs.Length > 0)
{
throw new Exception("Excel起動してたら動けねえよ!(怒)");
}
// Excelファイルを開く
xls_app = new Excel.Application();
work_book = (Excel.Workbook)(xls_app.Workbooks.Open(excel_path));
xls_app.Visible = false; // EXCEL非表示
xls_app.DisplayAlerts = false; // 終了確認非表示
// ワークシートを取得する
work_sheet = this.GetSheetIndex("Sheet1", work_book);
if (work_sheet == null)
{
throw new Exception("そんなシートねえよ!(怒)");
}
int row = 1; // 行 (1~)
int col = 1; // 列 (A~)
string value;
// ↓セル単体の読み書き
// セル「A1」の文字列を取得
value = this.GetCellString(work_sheet, row, col);
// セル「B2」に文字列を設定
this.SetCellString(work_sheet, row+1, col+1, value);
// ↓範囲系の処理
// セルコピー「C1~C9」
this.CellCopy(work_sheet, 3, 1, 3, 9);
// セル貼り付け「F1~F9」
this.CellPaste(work_sheet, 6, 1, 6, 9);
// セルクリア「I1~I9」
this.CellClear(work_sheet, 9, 1, 9, 9);
// …なんか他にもいろいろ操作あった気がするけど思い出したら追加しよう
// 編集した結果を保存
work_book.SaveAs(excel_path);
}
catch (Exception err)
{
// テキトーな解放処理
this.Release(work_book, xls_app);
// そのまま外に例外投げる
throw new Exception(err.Message);
}
// テキトーな解放処理
this.Release(work_book, xls_app);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment