日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程语言 > C# >内容正文

C#

C# 导出Word

發(fā)布時(shí)間:2024/8/22 C# 28 如意码农
生活随笔 收集整理的這篇文章主要介紹了 C# 导出Word 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

導(dǎo)出word文檔(無(wú)模版):

using Microsoft.Office.Interop.Word;

        public static string CreateWordFile(CaseVM model,string path)
{
string message = "";
try
{
Object Nothing = System.Reflection.Missing.Value;
//Directory.CreateDirectory("C:/CNSI"); //創(chuàng)建文件所在目錄
//string name = "CNSI_" + DateTime.Now.ToLongDateString() + ".doc";
object filename = path; //文件保存路徑
//創(chuàng)建Word文檔
Microsoft.Office.Interop.Word.Application WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
Microsoft.Office.Interop.Word.Document WordDoc = WordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing); //添加頁(yè)眉
WordApp.ActiveWindow.View.Type = WdViewType.wdOutlineView;
WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekPrimaryHeader;
WordApp.ActiveWindow.ActivePane.Selection.InsertAfter("[國(guó)泰安理財(cái)規(guī)劃大賽案例]");
WordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;//設(shè)置右對(duì)齊
WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekMainDocument;//跳出頁(yè)眉設(shè)置 WordApp.Selection.ParagraphFormat.LineSpacing = 15f;//設(shè)置文檔的行間距 //移動(dòng)焦點(diǎn)并換行
object count = ;
object WdLine = Microsoft.Office.Interop.Word.WdUnits.wdLine;//換一行;
WordApp.Selection.MoveDown(ref WdLine, ref count, ref Nothing);//移動(dòng)焦點(diǎn) // 插入段落
Microsoft.Office.Interop.Word.Paragraph para;
para = WordDoc.Content.Paragraphs.Add(ref Nothing); para.Range.Text = "案例信息";
//para.Range.Font.Size = 20;
para.Range.Font.Bold = ;
para.Range.Font.Color = WdColor.wdColorRed;
para.Range.Font.Italic = ;
para.Range.InsertParagraphAfter();
//WordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;//水平居中 para.Range.Text = "客戶姓名:" + model.CustomerName;
//para.Range.Font.Size = 12;
para.Range.Font.Bold = ;
para.Range.Font.Color = WdColor.wdColorBlack;
para.Range.Font.Italic = ;
para.Range.InsertParagraphAfter(); para.Range.Text = "身份證號(hào):" + model.IDNum;
para.Range.InsertParagraphAfter(); para.Range.Text = "理財(cái)類型:" + model.strFinancialType;
para.Range.InsertParagraphAfter(); para.Range.Text = "客戶背景:" + model.CustomerStory;
para.Range.InsertParagraphAfter(); WordApp.Selection.MoveDown(ref WdLine, ref count, ref Nothing);//移動(dòng)焦點(diǎn)
WordApp.Selection.MoveDown(ref WdLine, ref count, ref Nothing);//移動(dòng)焦點(diǎn) para.Range.Text = "考核點(diǎn)";
para.Range.Font.Bold = ;
para.Range.Font.Color = WdColor.wdColorRed;
para.Range.Font.Italic = ;
para.Range.InsertParagraphAfter();
WordApp.Selection.MoveDown(ref WdLine, ref count, ref Nothing);//移動(dòng)焦點(diǎn) para.Range.Font.Bold = ;
para.Range.Font.Color = WdColor.wdColorBlack;
para.Range.Font.Italic = ;
//文檔中創(chuàng)建表格
Microsoft.Office.Interop.Word.Table newTable = WordDoc.Tables.Add(WordApp.Selection.Range, , , ref Nothing, ref Nothing);
//設(shè)置表格樣式
newTable.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleThickThinLargeGap;
newTable.Borders.InsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
newTable.Columns[].Width = 50f;
newTable.Columns[].Width = 50f;
newTable.Columns[].Width = 160f;
newTable.Columns[].Width = 160f; //填充表格內(nèi)容
newTable.Cell(, ).Range.Text = "序號(hào)";
newTable.Cell(, ).Range.Bold = ;//設(shè)置單元格中字體為粗體
//合并單元格
//newTable.Cell(1, 1).Merge(newTable.Cell(1, 3));
WordApp.Selection.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;//垂直居中
WordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;//水平居中
newTable.Cell(, ).Range.Text = "類型";
newTable.Cell(, ).Range.Bold = ;//設(shè)置單元格中字體為粗體
//合并單元格
//newTable.Cell(1, 1).Merge(newTable.Cell(1, 3));
WordApp.Selection.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;//垂直居中
WordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;//水平居中
newTable.Cell(, ).Range.Text = "考點(diǎn)";
newTable.Cell(, ).Range.Bold = ;//設(shè)置單元格中字體為粗體
//合并單元格
//newTable.Cell(1, 1).Merge(newTable.Cell(1, 3));
WordApp.Selection.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;//垂直居中
WordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;//水平居中
newTable.Cell(, ).Range.Text = "答案";
newTable.Cell(, ).Range.Bold = ;//設(shè)置單元格中字體為粗體
//合并單元格
//newTable.Cell(1, 1).Merge(newTable.Cell(1, 3));
WordApp.Selection.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;//垂直居中
WordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;//水平居中 int i = ;
foreach (var item in model.ExamPointAnswer)
{
i++;
//填充表格內(nèi)容
newTable.Cell(i, ).Range.Text =(i-).ToString();
WordApp.Selection.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
newTable.Cell(i, ).Range.Text = item.strExamType;
WordApp.Selection.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
newTable.Cell(i, ).Range.Text = item.strExamPoint;
WordApp.Selection.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
newTable.Cell(i, ).Range.Text = item.Answer;
WordApp.Selection.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
} ////填充表格內(nèi)容
//newTable.Cell(2, 1).Range.Text = "產(chǎn)品基本信息";
//newTable.Cell(2, 1).Range.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorDarkBlue;//設(shè)置單元格內(nèi)字體顏色
////合并單元格
//newTable.Cell(2, 1).Merge(newTable.Cell(2, 3));
//WordApp.Selection.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; ////填充表格內(nèi)容
//newTable.Cell(3, 1).Range.Text = "品牌名稱:";
//newTable.Cell(3, 2).Range.Text = "BrandName";
////縱向合并單元格
//newTable.Cell(3, 3).Select();//選中一行
//object moveUnit = Microsoft.Office.Interop.Word.WdUnits.wdLine;
//object moveCount = 5;
//object moveExtend = Microsoft.Office.Interop.Word.WdMovementType.wdExtend;
//WordApp.Selection.MoveDown(ref moveUnit, ref moveCount, ref moveExtend);
//WordApp.Selection.Cells.Merge();
////////插入圖片
//////string FileName = @"c:\picture.jpg";//圖片所在路徑
//////object LinkToFile = false;
//////object SaveWithDocument = true;
//////object Anchor = WordDoc.Application.Selection.Range;
//////WordDoc.Application.ActiveDocument.InlineShapes.AddPicture(FileName, ref LinkToFile, ref SaveWithDocument, ref Anchor);
//////WordDoc.Application.ActiveDocument.InlineShapes[1].Width = 100f;//圖片寬度
//////WordDoc.Application.ActiveDocument.InlineShapes[1].Height = 100f;//圖片高度
////////將圖片設(shè)置為四周環(huán)繞型
//////Microsoft.Office.Interop.Word.Shape s = WordDoc.Application.ActiveDocument.InlineShapes[1].ConvertToShape();
//////s.WrapFormat.Type = Microsoft.Office.Interop.Word.WdWrapType.wdWrapSquare; //newTable.Cell(12, 1).Range.Text = "產(chǎn)品特殊屬性";
//newTable.Cell(12, 1).Merge(newTable.Cell(12, 3));
////在表格中增加行
//WordDoc.Content.Tables[1].Rows.Add(ref Nothing); //WordDoc.Paragraphs.Last.Range.Text = "文檔創(chuàng)建時(shí)間:" + DateTime.Now.ToString();//“落款”
//WordDoc.Paragraphs.Last.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight; //文件保存
WordDoc.SaveAs(ref filename, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing);
WordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
WordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
//message = name + "文檔生成成功,以保存到C:CNSI下";
}
catch
{
message = "文件導(dǎo)出異常!";
}
return message;
}

MS參照:http://www.cnblogs.com/haoxuan/articles/5135599.html

using Aspose.Words;

public static string CreateWordFile2(CaseVM model, string path)
{
string message = "";
try
{
Aspose.Words.Document doc = new Aspose.Words.Document();
DocumentBuilder builder = new DocumentBuilder(doc); builder.PageSetup.DifferentFirstPageHeaderFooter = true;
builder.PageSetup.OddAndEvenPagesHeaderFooter = true;
builder.MoveToHeaderFooter(HeaderFooterType.HeaderFirst);
builder.Font.Color = Color.Blue;
builder.Font.Size = ;
builder.Write("[國(guó)泰安理財(cái)規(guī)劃大賽案例]");
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center; builder.MoveToDocumentStart();
builder.ParagraphFormat.Alignment = ParagraphAlignment.Left;
builder.Font.Color = Color.Red;
builder.Font.Bold = true;
builder.Font.Italic = true;
builder.Writeln("案例信息");
builder.InsertBreak(BreakType.LineBreak); builder.Font.Color = Color.Black;
builder.Font.Bold = false;
builder.Font.Italic = false;
builder.Writeln("客戶姓名:" + model.CustomerName);
builder.Writeln("身份證號(hào):" + model.IDNum);
builder.Writeln("理財(cái)類型:" + model.strFinancialType);
builder.Writeln("客戶背景:" + model.CustomerStory);
builder.InsertBreak(BreakType.LineBreak); builder.Font.Color = Color.Red;
builder.Font.Bold = true;
builder.Font.Italic = true;
builder.Writeln("考核點(diǎn)");
builder.InsertBreak(BreakType.LineBreak);
builder.Font.Color = Color.Black;
builder.Font.Bold = false;
builder.Font.Italic = false; builder.CellFormat.Borders.LineStyle = LineStyle.Single;
builder.CellFormat.Borders.Color = Color.Black; builder.InsertCell();
builder.Write("序號(hào)");
builder.InsertCell();
builder.Write("類型");
builder.InsertCell();
builder.Write("考點(diǎn)");
builder.InsertCell();
builder.Write("答案");
builder.EndRow(); int i = ;
foreach (var item in model.ExamPointAnswer)
{
i++;
builder.InsertCell();
builder.Write((i - ).ToString());
builder.InsertCell();
builder.Write(item.strExamType == null ? "" : item.strExamType);
builder.InsertCell();
builder.Write(item.strExamPoint == null ? "" : item.strExamPoint);
builder.InsertCell();
builder.Write(item.Answer == null ? "" : item.Answer);
builder.EndRow();
}
builder.EndTable();
doc.Save(path); }
catch
{
message = "文件導(dǎo)出異常!";
}
return message;
}

Aspose參照(含源碼):http://blog.csdn.net/fraing/article/details/8989736

根據(jù)數(shù)據(jù)導(dǎo)出word文檔(有模版):

Aspose參照:http://www.cnblogs.com/jingshuisihan/p/4604260.html

MS參照:http://bbs.csdn.net/topics/390946804?page=1

導(dǎo)入xls/xlsx到DataTable:

HSSFWorkbook: http://www.cnblogs.com/songrun/p/3547738.html

OLEDB:

HDR=Yes,這代表第一行是標(biāo)題,不做為數(shù)據(jù)使用;IMEX ( IMport EXport mode )設(shè)置
  IMEX 有三種模式:
  0 is Export mode
  1 is Import mode
  2 is Linked mode (full update capabilities)
  我這里特別要說(shuō)明的就是 IMEX 參數(shù)了,因?yàn)椴煌哪J酱碇煌淖x寫(xiě)行為:
  當(dāng) IMEX=0 時(shí)為“匯出模式”,這個(gè)模式開(kāi)啟的 Excel 檔案只能用來(lái)做“寫(xiě)入”用途。
  當(dāng) IMEX=1 時(shí)為“匯入模式”,這個(gè)模式開(kāi)啟的 Excel 檔案只能用來(lái)做“讀取”用途。
  當(dāng) IMEX=2 時(shí)為“連結(jié)模式”,這個(gè)模式開(kāi)啟的 Excel 檔案可同時(shí)支援“讀取”與“寫(xiě)入”用途。

Aspose:

        /// <summary>
/// HSSFWorkbook讀取xls
/// </summary>
/// <param name="filepath">文件路徑</param>
/// <returns></returns>
public static DataTable GetExcelToDataTableByNPOI(string filepath)
{
NPOI.HSSF.UserModel.HSSFWorkbook hssworkbook;
using (FileStream file = new FileStream(filepath, FileMode.Open, FileAccess.Read))
{
hssworkbook = new NPOI.HSSF.UserModel.HSSFWorkbook(file);
}
ISheet sheet = hssworkbook.GetSheetAt();
IRow headerRow = sheet.GetRow();
int rowCount = sheet.LastRowNum;
int cellCount = headerRow.LastCellNum;
DataTable dt = new DataTable();
for (int j = ; j < cellCount; j++)
{
dt.Columns.Add(Convert.ToChar(((int)('A')) + j).ToString());
}
for (int r = (sheet.FirstRowNum + ); r <= rowCount; r++)
{
IRow row = sheet.GetRow(r); //讀取當(dāng)前行數(shù)據(jù)
if (row != null)
{
DataRow dr = dt.NewRow();
cellCount = row.LastCellNum;
bool isCellNull = true;
for (int i = ; i < cellCount; i++)
{
ICell cell = row.GetCell(i);
if (cell == null)
{
dr[i] = "";
}
else
{
cell.SetCellType(NPOI.SS.UserModel.CellType.STRING);
dr[i] = cell.StringCellValue;
if (isCellNull)
{
if (!string.IsNullOrWhiteSpace(cell.StringCellValue))
{
isCellNull = false;
}
}
}
}
if (!isCellNull)
{
dt.Rows.Add(dr);
}
}
}
return dt;
} /// <summary>
/// OleDb讀取xls/xlsx
/// </summary>
/// <param name="filepath">文件路徑</param>
/// <returns></returns>
public static DataTable GetExcelToDataTableByOleDb(string filepath)
{
string strCon = "";
if (filepath.IndexOf(".xlsx") != -)
strCon = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + filepath + ";" + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\"";
else if (filepath.IndexOf(".xls") != -)
strCon = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + filepath + ";" + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\""; string strCom = " SELECT * FROM [Sheet1$]"; DataTable dt_temp = new DataTable();
using (OleDbConnection myConn = new OleDbConnection(strCon))
using (OleDbDataAdapter myCommand = new OleDbDataAdapter(strCom, myConn))
{
myConn.Open();
myCommand.Fill(dt_temp);
} return dt_temp;
} /// <summary>
/// Aspose讀取xls/xlsx
/// </summary>
/// <param name="filepath">文件路徑</param>
/// <returns></returns>
public static DataTable GetExcelToDataTableByAspose(string filepath)
{
DataTable dt_temp = new DataTable();
try
{
Aspose.Cells.Workbook oBook = new Aspose.Cells.Workbook(filepath);
Cells cells = oBook.Worksheets[].Cells;
dt_temp = cells.ExportDataTable(, , cells.MaxDataRow + , cells.MaxColumn + );
}
catch (Exception ex)
{
}
return dt_temp;
}

總結(jié)

以上是生活随笔為你收集整理的C# 导出Word的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。