Skip to content

Instantly share code, notes, and snippets.

@thinkAmi
Created July 10, 2012 22:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thinkAmi/3086553 to your computer and use it in GitHub Desktop.
Save thinkAmi/3086553 to your computer and use it in GitHub Desktop.
MiBarcodeを使いExcel出力するサンプル
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
namespace MiBarcode
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string excelPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + @"\test.xls";
string exePath = @".\Mibarcd.exe";
Excel.Application app = new Excel.Application();
Excel.Workbook workbook = app.Workbooks.Add();
Excel.Worksheet sheet = (Excel.Worksheet)workbook.Sheets[1];
// 大文字と小文字混在では正しく出力されないため、大文字のみにする
string barcodeValue = "thinkAmi".ToUpper();
// Code128で、データ文字列あり、ビットマップ形式でコピー、サイズ2倍、出力したら終了
string args = barcodeValue + " /C128 /CC1 /CBM /TN2 /EXIT";
int rowIndex = 1;
int printCount = 1;
for (int i = 0; i < 3; i++)
{
System.Windows.Forms.Clipboard.Clear();
// A,D,G列に貼り付ける
int mod = printCount % 3;
switch (printCount % 3)
{
case 1:
sheet.get_Range(Cell1: "A" + rowIndex.ToString()).Select();
break;
case 2:
sheet.get_Range(Cell1: "D" + rowIndex.ToString()).Select();
break;
case 0:
sheet.get_Range(Cell1: "G" + rowIndex.ToString()).Select();
break;
default:
break;
}
System.Diagnostics.Process.Start(exePath, args);
// バーコードがクリップボードに転写されたら、Excelへとペーストする
// 10秒待っても転送されない場合は、処理しない
for (int waitCount = 0; waitCount < 10; waitCount++)
{
if (System.Windows.Forms.Clipboard.ContainsImage())
{
sheet.Paste();
break;
}
System.Threading.Thread.Sleep(1000);
}
printCount++;
System.Threading.Thread.Sleep(1000);
}
// 保存するときはファイルフォーマットを指定すること
// 指定しないと、正しいファイル定義ではない旨のエラーでExcelファイルを開けなくなる
workbook.SaveAs(Filename: excelPath, FileFormat: 56);
workbook.Close();
app.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(sheet);
sheet = null;
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
workbook = null;
System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
app = null;
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
MessageBox.Show("出力しました");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment