C# DataGridView 倒出word

來源:互聯網
上載者:User

public static void ExportToWord(DataGridView dgv, ProgressBar progress, SaveFileDialog savefile)
{
Microsoft.Office.Interop.Word.Document WordDoc = new Microsoft.Office.Interop.Word.Document();
Microsoft.Office.Interop.Word.Table WordTable;
object WordObj;
if (dgv.Rows.Count == 0)
{
return;
}
else
{
savefile.AddExtension = true;
savefile.DefaultExt = ".doc";
savefile.CreatePrompt = true;
savefile.Title = "匯出檔案儲存路徑";
savefile.Filter = "Word files (*.doc)|*.doc";
if (savefile.ShowDialog() == DialogResult.OK)
{
progress.Visible = true;
object path = savefile.FileName;
WordObj = System.Reflection.Missing.Value;
//建立word對象
Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
WordDoc = word.Documents.Add(ref WordObj, ref WordObj, ref WordObj, ref WordObj);
//建立表格
//將資料產生word表格檔案
WordTable = WordDoc.Tables.Add(WordDoc.Paragraphs.Last.Range, dgv.RowCount, dgv.ColumnCount, ref WordObj, ref WordObj);
WordTable.Columns.SetWidth(50, Microsoft.Office.Interop.Word.WdRulerStyle.wdAdjustNone);

try
{
for (int i = 0; i < dgv.Columns.Count; i++)//設定標題
{
WordTable.Cell(0, i + 1).Range.Text = dgv.Columns[i].HeaderText;
WordTable.Cell(0, i + 1).Range.Font.Size = 5;

}
for (int i = 1; i < dgv.Rows.Count; i++)//填充資料
{
for (int j = 0; j < dgv.Columns.Count; j++)
{
WordTable.Cell(i + 1, j + 1).Range.Text = dgv[j, i - 1].Value.ToString();
WordTable.Cell(i+1, j + 1).Range.Font.Size = 5;
}
progress.Value += 100 / dgv.RowCount;
}
WordDoc.SaveAs(ref path, ref WordObj, ref WordObj, ref WordObj, ref WordObj, ref WordObj, ref WordObj, ref WordObj, ref WordObj, ref WordObj, ref WordObj, ref WordObj, ref WordObj, ref WordObj, ref WordObj, ref WordObj);
WordDoc.Close(ref WordObj, ref WordObj, ref WordObj);
progress.Value = 100;
MessageBox.Show("資料已經成功匯出到:" + savefile.FileName.ToString(), "匯出完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
progress.Value = 0;
progress.Visible = false;
}
catch (Exception e)
{
MessageBox.Show(e.Message, "友情提示", MessageBoxButtons.OK);
}
finally
{
word.Quit(ref WordObj, ref WordObj, ref WordObj);
}

}
}
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.