Диплом: Автоматизация учета затрат на производство в компании ООО "Веллонс.Ру"

Внимание! Если размещение файла нарушает Ваши авторские права, то обязательно сообщите нам
117
179. this.шаблоныTableAdapter.Fill(this.bDDataSet.Шаблоны);
180. } private void Form1_Load(object sender, EventArgs e) {
181. // TODO: данная строка кода позволяет загрузить данные в таблицу
182. "bDDataSet1.Метки". При необходимости она может быть перемещена ил
и удалена.
183. this.меткиTableAdapter.Fill(this.bDDataSet1.Метки);
184. // TODO: данная строка кода позволяет загрузить данные в таблицу
185. "bDDataSet.ШаблонСтипом". При необходимости она может быть переме
щена или удалена.
186. this.шаблонСтипомTableAdapter.Fill(this.bDDataSet.ШаблонСтипом);
187. // TODO: данная строка кода позволяет загрузить данные в таблицу
188. "bDDataSet.Шаблоны". При необходимости она может быть перемещена
или удалена.
189. this.шаблоныTableAdapter.Fill(this.bDDataSet.Шаблоны);
190. //обнуляем выбор
191. comboBox1.BindingContext = new BindingContext();
192. comboBox1.SelectedIndex = -
1; } //Здесь хранится список меток и контролов, из которых брать данные для
их заполнения Dictionary<BDDataSet.МеткиRow, Control> dict = new
193. Dictionary<BDDataSet.МеткиRow, Control>();
194. //Здесь хранится список меток, которые относятся к типу Текущая дата и
время List<BDDataSet.МеткиRow> dictDatetime = new List<BDDataSet.МеткиRo
w>(); private void button1_Click(object sender, EventArgs e)
195. /// <summary>
196. /// Заполняем вордовский документ
197. /// </summary>
198. /// <param name="filename"></param>
199. /// <param name="sh"></param>
200. public Microsoft.Office.Interop.Word.Document FillWordDoc(string filename,
201. BDDataSet.ШаблонСтипомRow sh) {
202. Microsoft.Office.Interop.Word.Application ap = new
203. Microsoft.Office.Interop.Word.Application();
204. ap.Visible = false;
205. Document document = null;
206. try {
118
207. //ap.Documents.Close(filename);
208. document = ap.Documents.Open(filename);
209. //получаем список меток документа
210. foreach (BDDataSet.МеткиRow m in dict.Keys)
211. { document.Bookmarks[m.Наименование].Select();
212. Microsoft.Office.Interop.Word.Selection currentSelection = ap.Selection;
213. if (dict[m].GetType() == typeof(System.Windows.Forms.TextBox))
214. { System.Windows.Forms.TextBox t =
215. (System.Windows.Forms.TextBox)dict[m];
216. currentSelection.TypeText(string.IsNullOrEmpty(t.Text) ? "" : t.Text); } else {
217. //вставляем таблицу
218. DataGrid dgv = (DataGrid)dict[m];
219. document.Bookmarks[m.Наименование].Select();
220. System.Data.DataTable dt = (System.Data.DataTable)dgv.DataSource;
221. Microsoft.Office.Interop.Word.Table tbl1 =
222. ap.Selection.Tables.Add(ap.Selection.Range, 1, dt.Columns.Count);
223. //заголовки колонок
224. for (int i = 0; i <= dt.Columns.Count - 1; i++)
225. { tbl1.Cell(1, i + 1).Range.Text = dt.Columns[i].ColumnName;
226. tbl1.Cell(1, i + 1).Range.Borders[WdBorderType.wdBorderLeft].LineStyle
227. = WdLineStyle.wdLineStyleSingle;
228. tbl1.Cell(1, i +
229. 1).Range.Borders[WdBorderType.wdBorderRight].LineStyle = WdLineStyle.
wdLineStyleSingle;
230. tbl1.Cell(1, i + 1).Range.Borders[WdBorderType.wdBorderTop].LineStyle
231. = WdLineStyle.wdLineStyleSingle;
232. tbl1.Cell(1, i +
233. 1).Range.Borders[WdBorderType.wdBorderBottom].LineStyle = WdLineStyle
.wdLineStyleSingle; }
234. //строки таблицы
235. for (int i = 0; i <= dt.Rows.Count - 1; i++)
236. { tbl1.Rows.Add();
237. for (int j = 0; j <= dt.Columns.Count - 1; j++)
238. { tbl1.Cell(tbl1.Rows.Count, j + 1).Range.Text = dt.Rows[i][j] == null ? ""
239. : dt.Rows[i][j].ToString();
119
240. tbl1.Cell(tbl1.Rows.Count, j +
241. 1).Range.Borders[WdBorderType.wdBorderLeft].LineStyle = WdLineStyle.w
dLineStyleSingle;
242. tbl1.Cell(tbl1.Rows.Count, j +
243. 1).Range.Borders[WdBorderType.wdBorderRight].LineStyle = WdLineStyle.
wdLineStyleSingle;
244. tbl1.Cell(tbl1.Rows.Count, j +
245. 1).Range.Borders[WdBorderType.wdBorderTop].LineStyle = WdLineStyle.wd
LineStyleSingle;
246. tbl1.Cell(tbl1.Rows.Count, j +
247. 1).Range.Borders[WdBorderType.wdBorderBottom].LineStyle = WdLineStyle
.wdLineStyleSingle; } }101 } }
248. //получаем список меток с текущей датой и временем
249. foreach (BDDataSet.МеткиRow m in dictDatetime)
250. { document.Bookmarks[m.Наименование].Select();
251. Microsoft.Office.Interop.Word.Selection currentSelection = ap.Selection;
252. if (m.КодВидаМетки == 3)
253. currentSelection.TypeText(DateTime.Now.ToShortDateString());
254. if (m.КодВидаМетки == 4)
255. currentSelection.TypeText(DateTime.Now.ToShortTimeString()); }
256. //колонтитулы
257. ap.ActiveDocument.Sections[1].Footers[Microsoft.Office.Interop.Word.WdHe
aderFooterIndex.wd
258. HeaderFooterPrimary].Range.Text = textBox2.Text;
259. ap.ActiveDocument.Sections[1].Headers[Microsoft.Office.Interop.Word.WdH
eaderFooterIndex.wd
260. HeaderFooterPrimary].Range.Text = textBox1.Text;
261. //ReleaseObject(ap);
262. ap.Visible = true;
263. return document; }
264. catch (Exception ee)
265. { MessageBox.Show(ee.Message, "Возникла ошибка", MessageBoxButtons.
OK,
266. MessageBoxIcon.Error);
120
267. return null; } }
268. /// <summary>
269. /// Заполняем вордовский документ
270. /// </summary>
271. /// <param name="filename"></param>
272. /// <param name="sh"></param>
273. public string FillWordDocPacket(string filename, string filenameData)
274. { Microsoft.Office.Interop.Excel.Application apData = new
275. Microsoft.Office.Interop.Excel.Application();
276. apData.Visible = false;
277. Microsoft.Office.Interop.Excel.Workbook bookData = null;
278. Microsoft.Office.Interop.Excel.Workbooks databook = apData.Workbooks;
279. apData.Workbooks.Open(filenameData,
280. Type.Missing, Type.Missing, Type.Missing, Type.Missing,
281. Type.Missing, Type.Missing, Type.Missing, Type.Missing,
282. Type.Missing, Type.Missing, Type.Missing, Type.Missing,
283. Type.Missing, Type.Missing);
284. bookData = databook[1];
285. Microsoft.Office.Interop.Excel.Worksheet sheetData = bookData.Worksheets[
1];
286. Microsoft.Office.Interop.Word.Application ap = new
287. Microsoft.Office.Interop.Word.Application();
288. ap.Visible = false; string nameFold = "";
289. //создаем папку
290. nameFold = System.Windows.Forms.Application.StartupPath + @"\документ
ы\"
291. sh.Выражение1 + "_" + DateTime.Now.ToShortDateString().Replace(".", "-");
292. DirectoryInfo d;
293. if (!Directory.Exists(nameFold))
294. d = Directory.CreateDirectory(nameFold); else
295. { nameFold = System.Windows.Forms.Application.StartupPath + @"\докумен
ты\"+ sh.Выражение1 + "_" + DateTime.Now.ToShortDateString().Replace(".", "-
") + "-" +
296. DateTime.Now.ToShortTimeString().Replace(":", "-");
297. d = Directory.CreateDirectory(nameFold); }
121
298. for (int j = 7; j <= sheetData.UsedRange.Rows.Count - 1; j++)//строки
299. { if (sheetData.Cells[j, 1].value2 == null) continue; //нет порядковго номера
300. документа
301. string numberDoc = Convert.ToString(sheetData.Cells[j, 1].Value2);
302. //////////////новый документ
303. Document documentData = null;
304. documentData = ap.Documents.Open(filename);
305. //////////////
306. for (int i = 2; i <= sheetData.UsedRange.Columns.Count - 3; i++)//колонки
307. { string nameCol = sheetData.Cells[5, i].Value2 == null ? "" :
308. Convert.ToString(sheetData.Cells[5, i].Value2);
309. if (nameCol == "") continue;
310. DataRow[] dr = bDDataSet1.Метки.Select("КодШаблона=" + sh.КодШабло
на
311. + " and Наименование='" + nameCol + "'");
312. if (dr == null || dr.Length == 0) continue;
313. BDDataSet.МеткиRow metka = ((BDDataSet.МеткиRow)dr[0]);
314. int vidMetka = metka.КодВидаМетки;
315. documentData.Bookmarks[metka.Наименование].Select();
316. Microsoft.Office.Interop.Word.Selection currentSelection = ap.Selection;
317. if (vidMetka == 1)
318. { currentSelection.TypeText(sheetData.Cells[j, i].Value2 == null ? "" :
319. Convert.ToString(sheetData.Cells[j, i].Value2)); }
320. //текущая дата
321. if (vidMetka == 3)
322. currentSelection.TypeText(DateTime.Now.ToShortDateString());
323. //текущее время
324. if (vidMetka == 4)
325. currentSelection.TypeText(DateTime.Now.ToShortTimeString());
326. if (vidMetka == 2) {
327. ///вставляем таблицу
328. string[] s = metka.ЗаголовкиКолонок.Split('/');
329. //int row = b.RefersToRange.Row;
330. // int col = b.RefersToRange.Column;
331. int rowsCount = 0;
122
332. int colCount = s.Length;
333. for (int k = j + 1; k <= sheetData.UsedRange.Rows.Count - 1; k++)
334. { if (sheetData.Cells[k, 1].Value2 != null)
335. { rowsCount = (k - j) ;
336. break; } }
337. if (rowsCount == 0) rowsCount = sheetData.UsedRange.Rows.Count - j +1;
338. documentData.Bookmarks[metka.Наименование].Select();
339. Microsoft.Office.Interop.Word.Table tbl1 =
340. ap.Selection.Tables.Add(ap.Selection.Range, 1, colCount);
341. ////заголовки колонок
342. for (int c = 0; c <= colCount - 1; c++)
343. { tbl1.Cell(1, c + 1).Range.Text = s[c];
344. tbl1.Cell(1, c + 1).Range.Borders[WdBorderType.wdBorderLeft].LineStyle
345. = WdLineStyle.wdLineStyleSingle;
346. tbl1.Cell(1, c +
347. 1).Range.Borders[WdBorderType.wdBorderRight].LineStyle = WdLineStyle.
wdLineStyleSingle;
348. tbl1.Cell(1, c + 1).Range.Borders[WdBorderType.wdBorderTop].LineStyle
349. = WdLineStyle.wdLineStyleSingle;
350. tbl1.Cell(1, c +
351. 1).Range.Borders[WdBorderType.wdBorderBottom].LineStyle = WdLineStyle
.wdLineStyleSingle; }
352. ////строки таблицы
353. for (int r = 0; r <= rowsCount - 1; r++)
354. { tbl1.Rows.Add();
355. for (int m = 0; m <= colCount - 1; m++)
356. { tbl1.Cell(tbl1.Rows.Count, m + 1).Range.Text = sheetData.Cells[j + r, i
357. + m].Value2 == null ? "" : Convert.ToString(sheetData.Cells[j + r, i + m].Valu
e2);
358. tbl1.Cell(tbl1.Rows.Count, m +
359. 1).Range.Borders[WdBorderType.wdBorderLeft].LineStyle = WdLineStyle.w
dLineStyleSingle;
360. tbl1.Cell(tbl1.Rows.Count, m +
361. 1).Range.Borders[WdBorderType.wdBorderRight].LineStyle = WdLineStyle.
wdLineStyleSingle;
123
362. tbl1.Cell(tbl1.Rows.Count, m +
363. 1).Range.Borders[WdBorderType.wdBorderTop].LineStyle = WdLineStyle.wd
LineStyleSingle;
364. tbl1.Cell(tbl1.Rows.Count, m +
365. 1).Range.Borders[WdBorderType.wdBorderBottom].LineStyle = WdLineStyle
.wdLineStyleSingle; } } } }
366. //сохраняем документ
367. //колонтитулы
368. ap.ActiveDocument.Sections[1].Footers[Microsoft.Office.Interop.Word.WdHe
aderFooterIndex.wd
369. HeaderFooterPrimary].Range.Text = sheetData.Cells[2, 3].value2 == null ? "" :
sheetData.Cells[2,
370. 3].value2; ap.ActiveDocument.Sections[1].Headers[Microsoft.Office.Interop.
Word.WdHeaderFooterIndex.wd
371. HeaderFooterPrimary].Range.Text = sheetData.Cells[1, 3].value2 == null ? "" :
sheetData.Cells[1,3].value2; ;
372. //получаем список меток с текущей датой и временем
373. DataRow[] dr1 = bDDataSet1.Метки.Select("КодШаблона=" + sh.КодШабло
на
374. + " and (КодВидаМетки=3 or КодВидаМетки=4)");
375. foreach (BDDataSet.МеткиRow m in dr1)
376. { documentData.Bookmarks[m.Наименование].Select();
377. Microsoft.Office.Interop.Word.Selection currentSelection = ap.Selection;
378. if (m.КодВидаМетки == 3)
379. currentSelection.TypeText(DateTime.Now.ToShortDateString());
380. if (m.КодВидаМетки == 4)
381. currentSelection.TypeText(DateTime.Now.ToShortTimeString()); }
382. documentData.SaveAs(d.FullName + @"\" + numberDoc + ".docx");
383. documentData.Close();
384. if(checkBox1.Checked && sheetData.Cells[j,
385. sheetData.UsedRange.Columns.Count - 2].Value2 != null )
386. { string email = sheetData.Cells[j, sheetData.UsedRange.Columns.Count -
387. 2].Value2 == null ? "" : Convert.ToString(sheetData.Cells[j, sheetData.UsedRa
nge.Columns.Count -2].Value2);
388. string tema = sheetData.Cells[j, sheetData.UsedRange.Columns.Count -
124
389. 1].Value2 == null ? "" : Convert.ToString(sheetData.Cells[j, sheetData.UsedRa
nge.Columns.Count -1].Value2);
390. string text = sheetData.Cells[j, sheetData.UsedRange.Columns.Count].Value2
391. == null ? "" : Convert.ToString(sheetData.Cells[j, sheetData.UsedRange.Colu
mns.Count ].Value2);
392. ClassEmail.SendMail("smtp.mail.ru", "test-diplom-2017@mail.ru", "test2017",
393. email,tema, text, d.FullName + @"\" + numberDoc + ".docx");
394. } } ap.Quit();
395. apData.Quit();
396. return d.FullName;
397. } void ReleaseObject(object obj)
398. { try { Marshal.ReleaseComObject(obj);
399. obj = null;
400. } catch (Exception ex)
401. { MessageBox.Show(@"Unable to release the object " + ex);
402. obj = null;
403. } finally { GC.Collect(); } }
404. /// <summary>
405. /// Заполняем экселевский документ
406. ///
407. /// <param name="filename"></param>
408. /// <param name="sh"></param>
409. public Microsoft.Office.Interop.Excel.Worksheet FillExcelDoc(string filename
,
410. BDDataSet.ШаблонСтипомRow sh) {
411. Microsoft.Office.Interop.Excel.Application ap = new
412. Microsoft.Office.Interop.Excel.Application();
413. ap.Visible = false;
414. Microsoft.Office.Interop.Excel.Workbook book = null;
415. try {
416. Microsoft.Office.Interop.Excel.Workbooks excelappworkbooks = ap.Workboo
ks;
417. ap.Workbooks.Open(filename,
418. Type.Missing, Type.Missing, Type.Missing, Type.Missing,
419. Type.Missing, Type.Missing, Type.Missing, Type.Missing,
125
420. Type.Missing, Type.Missing, Type.Missing, Type.Missing,
421. Type.Missing, Type.Missing);
422. book = excelappworkbooks[1];
423. //получаем список меток документа
424. Microsoft.Office.Interop.Excel.Worksheet sheet = book.Worksheets[1];
425. this.меткиTableAdapter.Fill(this.bDDataSet1.Метки);
426. foreach (BDDataSet.МеткиRow m in dict.Keys) {
427. //ищем нужную метку
428. foreach (Microsoft.Office.Interop.Excel.Name b in ap.Names)

Смотрите также:

"Автоматизация обработки заявок ООО "Проектно-Строительная Компания"
"Автоматизация процесса аттестации персонала для ООО "Нэт Бай Нэт Холдинг"
"Анализ интернет-активности конкурентов ( на примере конкурентов "Газпром нефть")
"Бухгалтерский учёт и аудит расчётов с подотчётними лицами в организации на примере ООО "ЛОЦ 10""
«Психологическое сопровождение персонала в организации на примере ООО «Крокус»
«Управление ресурсами проекта» (на примере организации ООО «ЛАКОСТЭ»)
Agile-методология в управлении проектами на примере ООО «Ресурсный центр «Академия КлассИнфо»
Aвтoмaтизaция пpoцecca вeдeния инфopмaциoннoй бaзы o дoлжнocтяx и вaкaнcияx c укaзaниeм тpeбoвaний к уpoвню знaний и нaвыкoв кaндидaтoв для гpуппы кaдpoв вoйcкoвoй чacти 3474»
Cовершенствование деловой оценки персонала в организации (на примере ООО "Даймонд кейтеринг развитие")
Cовершенствование управления рентабельности предприятия (на примере гуипп «бендерская типография «полиграфист»)