C#を学び始めて2週間くらいです。
SQLのDBの内容を既存のエクセルファイルをSFDで手動で選び上書き保存をしたいんですが,
・現在の状況としてデバックで操作して全体的な動作はするが、データが一切書き込まれず、既存のエクセルファイルがロックされてしまい読み取り専用になってしまう。
・while文のところだけ動作をしない。
ご教授頂きたいです。
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.IO; using Microsoft.Office.Core; using System.Data.SqlClient; using Microsoft.Office.Interop.Excel; namespace 課題1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } //DB接続用 SqlConnection con = new SqlConnection(); SqlCommand com = new SqlCommand(); private void button1_Click(object sender, EventArgs e) { con.ConnectionString = "割愛 //接続先を開く con.Open(); //SQL文を発行する SqlCommand com = new SqlCommand("割愛); //SQLを実行する。 SqlDataReader reader = com.ExecuteReader(); System.IO.FileInfo fi = new System.IO.FileInfo(@ファイルのパスを入れてます"); //Excelファイルのパス Microsoft.Office.Interop.Excel.Application Ex = new Microsoft.Office.Interop.Excel.Application(); //ファイルを開く Microsoft.Office.Interop.Excel.Workbook wb = Ex.Workbooks.Open(Filename: fi.FullName); try { //Sheetを指定 ((Worksheet)wb.Sheets[1]).Select(); } catch(Exception ) { //エラー処理 //Appを閉じる wb.Close(false); Ex.Quit(); } //変数宣言 Range CellRange; int i = 0; //DBからデータを読み込む while (reader.Read()) { for (int l = 0; l < 10; l++) { CellRange =Ex.Cells[i + 2, l + 1] as Range; CellRange.Value2 = reader.GetValue(l); } i++; } SaveFileDialog SFD = new SaveFileDialog(); SFD.Filter = "Excelファイル|*.xls"; if (SFD.ShowDialog() != DialogResult.OK) { return; } //Appを閉じる wb.Close(true); Ex.Quit(); } private void button2_Click(object sender, EventArgs e) { this.Close(); }
回答1件
あなたの回答
tips
プレビュー